use datafusion::common::stats::Precision;
use datafusion::common::tree_node::TreeNodeRecursion;
use datafusion::common::{Result, exec_err, internal_err};
use datafusion::physical_expr::expressions::Column;
use datafusion::physical_plan::ColumnStatistics;
use datafusion::physical_plan::PhysicalExpr;
use datafusion::physical_plan::execution_plan::{
ChildrenPropertiesMode, ReplaceChildrenOptions, Statistics,
};
use datafusion::physical_plan::metrics::{ExecutionPlanMetricsSet, MetricsSet};
use datafusion::physical_plan::repartition::RepartitionExec;
use datafusion::physical_plan::sorts::sort::SortExec;
use datafusion::physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec;
use datafusion::physical_plan::statistics::{ChildStats, StatisticsArgs};
use datafusion::physical_plan::{
DisplayAs, DisplayFormatType, ExecutionPlan, InputDistributionRequirements,
SendableRecordBatchStream, apply_expression_roots,
};
use datafusion_hash_grouped_order::{
BoundedPartitionFilter, GroupEmitOrder, GroupedOrderConsumer, GroupedOrderTarget,
HashGroupedOrderExec, HashGroupedOrderRule, PartitionMaskExtractor,
};
use std::num::NonZeroUsize;
use std::sync::Arc;
use crate::config::MatchRecognizeConfig;
use crate::execution::physical::halo::{
HALO_CHUNK_ID, HALO_GROUP_ID, HaloChunkExec, HaloFinalizeExec,
};
use crate::execution::physical::properties::{
calc_requirements, get_partition_by_sort_exprs,
};
use crate::core::{EmptyMatchesMode, RowsPerMatch};
use crate::execution::matching::{
ExecutableMatchProgram, ExecutableOutputFinalizer, ResolvedAfterMatchSkip,
};
use crate::nfa::PatternCompileLimits;
use crate::nfa_executor::{ExecutePatternInput, execute_pattern};
use datafusion::physical_expr_common::sort_expr::{
LexOrdering, OrderingRequirements, PhysicalSortExpr,
};
mod construction;
mod display;
mod synthetic_row_filter;
pub use synthetic_row_filter::try_absorb_synthetic_row_filter;
pub(crate) use construction::PreparedPattern;
pub(crate) use construction::{
MatchPlanLayout, PatternPreparationInput, prepare_pattern, runtime_symbol_ids,
validate_compiled_symbol_alignment,
};
pub(crate) use display::MatchPlanDisplay;
use display::format_exec_display;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum PartitionRetention {
ThresholdSafe,
LogicalPartitionBoundaryOnly,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct HaloQualification {
max_match_len: NonZeroUsize,
}
impl HaloQualification {
fn for_program(program: &ExecutableMatchProgram) -> Option<Self> {
let automaton = program.compiled_automaton();
if !program.can_skip_candidate_evaluation
|| program.offset_columns.is_some()
|| program
.classification
.as_ref()
.is_some_and(|c| c.needs_neighbors())
|| automaton.has_anchors()
|| !program.stream_requirements().independent_candidate_starts
|| automaton.min_match_rows() == 0
{
return None;
}
let max_match_len = NonZeroUsize::new(automaton.max_match_rows()?)?;
let independent_skip = match program.after_match_skip() {
ResolvedAfterMatchSkip::ToNextRow => true,
ResolvedAfterMatchSkip::PastLastRow => {
max_match_len.get() == 1 || program.non_overlapping_starts
}
_ => false,
};
if !independent_skip || !program.output_spec().navigation_offsets().is_zero() {
return None;
}
match program.rows_per_match() {
RowsPerMatch::OneRow
| RowsPerMatch::AllRows(EmptyMatchesMode::Show | EmptyMatchesMode::Omit) => {
Some(Self { max_match_len })
}
RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched) => None,
}
}
pub(crate) const fn max_match_len(self) -> usize {
self.max_match_len.get()
}
}
impl PartitionRetention {
pub(crate) fn for_program(program: &ExecutableMatchProgram) -> Self {
if program.compiled_automaton().has_end_anchor()
|| program.stream_requirements().needs_complete_partition
{
Self::LogicalPartitionBoundaryOnly
} else {
Self::ThresholdSafe
}
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct PlannedRuntimePolicy {
pattern_compile_limits: PatternCompileLimits,
compact_paths_disabled: bool,
retention: PartitionRetention,
parallel_qualification: Option<HaloQualification>,
}
impl PlannedRuntimePolicy {
pub(crate) fn new(
bound: &BoundMatchPlan,
pattern_compile_limits: PatternCompileLimits,
compact_paths_disabled: bool,
) -> Self {
let program = bound.program.as_ref();
Self {
pattern_compile_limits,
compact_paths_disabled,
retention: PartitionRetention::for_program(program),
parallel_qualification: HaloQualification::for_program(program),
}
}
pub(crate) const fn retention(self) -> PartitionRetention {
self.retention
}
pub(crate) const fn parallel_qualification(self) -> Option<HaloQualification> {
self.parallel_qualification
}
pub(in crate::execution) fn apply(
self,
mut config: MatchRecognizeConfig,
) -> MatchRecognizeConfig {
config.diagnostics.disable_compact_paths |= self.compact_paths_disabled;
config.limits.pattern_max_permute_branches =
self.pattern_compile_limits.max_permute_branches;
config.limits.pattern_max_nfa_states = self.pattern_compile_limits.max_nfa_states;
config.limits.pattern_max_epsilon_closure_entries =
self.pattern_compile_limits.max_epsilon_closure_entries;
config.limits.pattern_max_dense_transition_cells =
self.pattern_compile_limits.max_dense_transition_cells;
config
}
fn for_halo(self) -> Self {
Self {
retention: PartitionRetention::LogicalPartitionBoundaryOnly,
parallel_qualification: None,
..self
}
}
}
#[derive(Clone, Debug)]
pub(in crate::execution) struct BoundMatchPlan {
layout: MatchPlanLayout,
program: Arc<ExecutableMatchProgram>,
display: MatchPlanDisplay,
}
impl BoundMatchPlan {
pub(in crate::execution) fn from_checked_parts(
layout: MatchPlanLayout,
program: Arc<ExecutableMatchProgram>,
display: MatchPlanDisplay,
) -> Self {
Self {
layout,
program,
display,
}
}
}
#[derive(Debug)]
pub struct MatchRecognizePatternExec {
bound: BoundMatchPlan,
policy: PlannedRuntimePolicy,
raw_float_groups: bool,
candidate_start_core_rows: Option<NonZeroUsize>,
metrics: ExecutionPlanMetricsSet,
}
impl MatchRecognizePatternExec {
pub(super) fn with_match_aware_input(
mut self,
mr: &crate::planning::logical::MatchRecognize,
allow_windows: bool,
binder: &mut crate::execution::physical::planner::bind::PhysicalMatchBinder<'_>,
) -> Result<Self> {
use crate::execution::physical::{classification, virtual_input};
let aware = self.bound.program.as_ref();
let layout = &self.bound.layout;
let order = layout.order_by.as_deref().unwrap_or_default();
let bound = classification::bind_post_order_input(
&layout.input,
aware,
mr,
&layout.partition_by,
order,
allow_windows,
)?;
let had_classification = bound.is_some();
let mut bound = bound.unwrap_or_else(|| classification::BoundInput {
input: layout.input.clone(),
classification: None,
offsets: None,
rules: Vec::new(),
unused_window_columns: std::collections::HashSet::new(),
});
let compact = if allow_windows {
virtual_input::compact(mr, aware, &mut bound, &layout.partition_by, order)?
} else {
None
};
if !had_classification && compact.is_none() {
return Ok(self);
}
let mapping = if let Some(compact) = compact {
if let Some((logical, full)) = compact.rebound {
let bypass =
self.bound.layout.bypass_never_ordering && !self.raw_float_groups;
self.bound = binder.bind(&logical, &[full])?;
self.bound.layout = self
.bound
.layout
.rebuild_with_bypass(bypass, self.bound.program.as_ref())?;
}
bound.input = compact.input;
Some(Arc::new(compact.mapping))
} else {
None
};
let program = Arc::make_mut(&mut self.bound.program);
let aware = &mut *program;
aware.virtual_input = mapping;
aware.pre_sort_filter = None;
if let Some(classification) = bound.classification {
if aware.can_skip_candidate_evaluation {
if bound.offsets.is_none() {
aware.pre_sort_filter = classification.partition_filter(
aware.base_variant().automaton().required_anchors(),
);
}
aware.packed_anchors =
crate::execution::classification::PackedAnchors::bind(
&classification,
aware.base_variant().automaton(),
)
.map(Arc::new);
}
aware.classification = Some(Arc::new(classification));
}
aware.offset_columns = bound.offsets.map(Arc::new);
self.policy.parallel_qualification = HaloQualification::for_program(aware);
self.bound.layout = self.bound.layout.rebuild_with_input(bound.input, program)?;
Ok(self)
}
fn rebuild_with_child(
&self,
input: Arc<dyn ExecutionPlan>,
properties_mode: ChildrenPropertiesMode,
) -> Result<Self> {
if input.schema() != self.bound.layout.input.schema() {
return internal_err!(
"MATCH_RECOGNIZE replacement child schema must equal the prepared input schema"
);
}
let layout = match properties_mode {
ChildrenPropertiesMode::Keep
if self.grouped_input().is_none()
&& input.downcast_ref::<HashGroupedOrderExec>().is_none() =>
{
MatchPlanLayout {
input,
..self.bound.layout.clone()
}
}
_ => self
.bound
.layout
.rebuild_with_input(input, self.program().as_ref())?,
};
Ok(Self {
bound: BoundMatchPlan::from_checked_parts(
layout,
Arc::clone(self.program()),
self.bound.display.clone(),
),
policy: self.policy,
raw_float_groups: self.raw_float_groups,
candidate_start_core_rows: self.candidate_start_core_rows,
metrics: ExecutionPlanMetricsSet::new(),
})
}
pub(super) fn new(bound: BoundMatchPlan, policy: PlannedRuntimePolicy) -> Self {
Self {
bound,
policy,
raw_float_groups: false,
candidate_start_core_rows: None,
metrics: ExecutionPlanMetricsSet::new(),
}
}
pub(super) fn with_raw_float_groups(mut self, raw_float_groups: bool) -> Self {
self.raw_float_groups = raw_float_groups;
if raw_float_groups && self.bound.layout.bypass_never_ordering {
self.bound.layout = self
.bound
.layout
.rebuild_with_bypass(false, self.program().as_ref())
.expect("recomputing layout for raw float groups");
}
self
}
pub(crate) fn with_candidate_start_core_rows(
mut self,
core_rows: NonZeroUsize,
) -> Self {
self.candidate_start_core_rows = Some(core_rows);
if self.bound.layout.bypass_never_ordering {
self.bound.layout = self
.bound
.layout
.rebuild_with_bypass(false, self.program().as_ref())
.expect("recomputing layout for halo core rows");
}
self
}
pub(crate) fn into_halo_pipeline(
self,
core_rows: NonZeroUsize,
output_partitions: usize,
qualification: HaloQualification,
private_chunk: bool,
) -> Result<Arc<dyn ExecutionPlan>> {
if output_partitions == 0 {
return internal_err!(
"MATCH_RECOGNIZE halo pipeline requires an output partition"
);
}
let original_program = Arc::clone(self.program());
let needs_match_numbers = original_program
.output_plan()
.match_number_column()
.is_some();
let original_ordering = self.bound.layout.order_by.clone();
let partition_by = self.bound.layout.partition_by.clone();
let keyed = !partition_by.is_empty();
let required_input_ordering = if keyed {
let mut required_ordering = self.partition_by_sort_keys()?;
if let Some(ordering) = &original_ordering {
for sort_expr in ordering {
if !required_ordering
.iter()
.any(|existing| existing.expr.eq(&sort_expr.expr))
{
required_ordering.push(sort_expr.clone());
}
}
}
LexOrdering::new(required_ordering)
} else {
original_ordering.clone()
};
let halo = HaloChunkExec::try_new(
Arc::clone(&self.bound.layout.input),
required_input_ordering,
original_ordering.clone(),
partition_by,
core_rows.get(),
qualification.max_match_len(),
)?;
let group_input_index = halo.group_column_index();
let chunk_input_index = halo.chunk_column_index();
let schema_without_chunk = halo.schema_without_chunk();
let halo: Arc<dyn ExecutionPlan> = Arc::new(halo);
let group_input_expr = group_input_index.map(|index| {
Arc::new(Column::new(HALO_GROUP_ID, index)) as Arc<dyn PhysicalExpr>
});
let chunk_input_expr = Arc::new(Column::new(HALO_CHUNK_ID, chunk_input_index))
as Arc<dyn PhysicalExpr>;
let mut private_input_exprs = Vec::with_capacity(1 + usize::from(keyed));
if let Some(group_input_expr) = &group_input_expr {
private_input_exprs.push(Arc::clone(group_input_expr));
}
private_input_exprs.push(Arc::clone(&chunk_input_expr));
let repartition = RepartitionExec::try_new(
halo,
datafusion::physical_plan::Partitioning::Hash(
private_input_exprs.clone(),
output_partitions,
),
)?
.with_preserve_order();
let repartition: Arc<dyn ExecutionPlan> = Arc::new(repartition);
let halo_program = Arc::new(if private_chunk {
original_program
.with_appended_passthrough(&repartition.schema(), chunk_input_index)?
} else if needs_match_numbers {
let with_group = match group_input_index {
Some(group_input_index) => original_program.with_appended_passthrough(
&schema_without_chunk,
group_input_index,
)?,
None => original_program.as_ref().clone(),
};
with_group
.with_appended_passthrough(&repartition.schema(), chunk_input_index)?
} else {
original_program.with_extended_input_schema(&repartition.schema())?
});
let layout = MatchPlanLayout::try_new(
repartition,
private_input_exprs,
original_ordering,
halo_program.as_ref(),
)?;
let match_number_column = halo_program
.output_plan()
.match_number_column()
.map(|column| column.index());
let matcher = MatchRecognizePatternExec::new(
BoundMatchPlan::from_checked_parts(
layout,
halo_program,
self.bound.display.clone(),
),
self.policy.for_halo(),
)
.with_candidate_start_core_rows(core_rows);
let matcher: Arc<dyn ExecutionPlan> = Arc::new(matcher);
if private_chunk {
let chunk = original_program
.output_spec()
.passthrough_input_indices()
.len();
return super::halo::project_group_chunk(matcher, Some(chunk));
}
if match_number_column.is_none() {
return Ok(matcher);
}
let original_schema = Arc::clone(original_program.output_schema());
let first_hidden_output_index = original_program
.output_spec()
.passthrough_input_indices()
.len();
let group_output_index = keyed.then_some(first_hidden_output_index);
let chunk_output_index = first_hidden_output_index + usize::from(keyed);
let mut merge_ordering = Vec::with_capacity(1 + usize::from(keyed));
if let Some(group_output_index) = group_output_index {
merge_ordering.push(PhysicalSortExpr {
expr: Arc::new(Column::new(HALO_GROUP_ID, group_output_index)),
options: datafusion::arrow::compute::SortOptions::new(false, false),
});
}
merge_ordering.push(PhysicalSortExpr {
expr: Arc::new(Column::new(HALO_CHUNK_ID, chunk_output_index)),
options: datafusion::arrow::compute::SortOptions::new(false, false),
});
let chunk_output_ordering = LexOrdering::new(merge_ordering)
.expect("halo merge key makes the ordering nonempty");
let merged: Arc<dyn ExecutionPlan> =
Arc::new(SortPreservingMergeExec::new(chunk_output_ordering, matcher));
let finalized = HaloFinalizeExec::try_new(
merged,
original_schema,
group_output_index,
chunk_output_index,
match_number_column,
)?;
Ok(Arc::new(finalized))
}
pub(crate) fn program(&self) -> &Arc<ExecutableMatchProgram> {
&self.bound.program
}
pub(in crate::execution) const fn policy(&self) -> PlannedRuntimePolicy {
self.policy
}
pub fn partition_by_sort_keys(&self) -> Result<Vec<PhysicalSortExpr>> {
if let Some(group) = self.grouped_input() {
return Ok(group
.output_group_keys()
.iter()
.zip(group.partition_sort_options())
.map(|(expr, options)| PhysicalSortExpr::new(Arc::clone(expr), *options))
.collect());
}
if self.can_bypass_ordering_for_never() {
return Ok(vec![]);
}
if self.bound.layout.ordered_partition_by_indices.len()
!= self.bound.layout.partition_by.len()
{
return exec_err!(
"MATCH_RECOGNIZE requires ordered input covering every PARTITION BY key"
);
}
get_partition_by_sort_exprs(
&self.bound.layout.input,
&self.bound.layout.partition_by,
&self.bound.layout.ordered_partition_by_indices,
)
}
pub fn partition_keys(&self) -> Vec<Arc<dyn PhysicalExpr>> {
self.bound.layout.partition_by.clone()
}
fn can_bypass_ordering_for_never(&self) -> bool {
self.bound.layout.bypass_never_ordering
&& self.candidate_start_core_rows.is_none()
&& !self.raw_float_groups
}
}
impl DisplayAs for MatchRecognizePatternExec {
fn fmt_as(
&self,
_t: DisplayFormatType,
f: &mut std::fmt::Formatter,
) -> std::fmt::Result {
format_exec_display(self, f)
}
}
impl ExecutionPlan for MatchRecognizePatternExec {
fn name(&self) -> &'static str {
Self::static_name()
}
fn properties(
&self,
) -> &Arc<datafusion::physical_plan::execution_plan::PlanProperties> {
&self.bound.layout.cache
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![&self.bound.layout.input]
}
fn apply_expressions(
&self,
f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
) -> Result<TreeNodeRecursion> {
let program_roots = self.program().physical_expr_roots();
let layout_roots = self.bound.layout.partition_by.iter();
apply_expression_roots(layout_roots.chain(program_roots.iter()), f)
}
fn replace_children(
self: Arc<Self>,
mut children: Vec<Arc<dyn ExecutionPlan>>,
options: ReplaceChildrenOptions,
) -> Result<Arc<dyn ExecutionPlan>> {
if children.len() != 1 {
return internal_err!(
"MatchRecognizePatternExec expected 1 child, got {}",
children.len()
);
}
let input = children.swap_remove(0);
Ok(Arc::new(
self.rebuild_with_child(input, options.children_properties)?,
))
}
fn with_new_children(
self: Arc<Self>,
children: Vec<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
self.replace_children(
children,
ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
)
}
fn execute(
&self,
partition: usize,
context: Arc<datafusion::execution::TaskContext>,
) -> Result<SendableRecordBatchStream> {
log::debug!("Executing MatchRecognizePatternExec for partition {partition}");
let flush_threshold = context.session_config().batch_size();
let mr_config = context
.session_config()
.options()
.extensions
.get::<MatchRecognizeConfig>()
.cloned()
.unwrap_or_default();
let mr_config = self.policy.apply(mr_config);
use crate::execution::stream::MatchInput;
let input_stream = match self.grouped_input() {
Some(grouped) => {
let needed = Some(
self.program()
.referenced_input_columns(grouped.schema().fields().len()),
);
MatchInput::Grouped(grouped.execute_grouped_with_needed_columns(
partition,
Arc::clone(&context),
needed,
)?)
}
None => MatchInput::Ordered(
self.bound
.layout
.input
.execute(partition, Arc::clone(&context))?,
),
};
log::debug!(
"Calling execute_pattern with interleaves_logical_partitions={}",
self.program()
.stream_requirements()
.interleaves_logical_partitions
);
execute_pattern(ExecutePatternInput {
input: input_stream,
program: Arc::clone(&self.bound.program),
partition_by_sort_keys: self.partition_by_sort_keys()?,
retention: self.policy.retention(),
candidate_start_core_rows: self.candidate_start_core_rows,
output_batch_size: self
.candidate_start_core_rows
.and_then(|core| NonZeroUsize::new(core.get().max(flush_threshold))),
flush_threshold,
config: mr_config,
metrics_set: self.metrics.clone(),
task_context: context,
partition,
})
}
fn child_stats_requests(&self, partition: Option<usize>) -> Vec<ChildStats> {
vec![ChildStats::At(partition)]
}
fn statistics_from_inputs(
&self,
input_stats: &[Arc<Statistics>],
_args: &StatisticsArgs,
) -> Result<Arc<Statistics>> {
let [input_stats] = input_stats else {
return internal_err!(
"MatchRecognizePatternExec expected statistics for 1 child, got {}",
input_stats.len()
);
};
Ok(Arc::new(compute_partition_statistics(
input_stats.as_ref(),
self.program(),
)))
}
fn required_input_ordering(&self) -> Vec<Option<OrderingRequirements>> {
if self.grouped_input().is_some() || self.can_bypass_ordering_for_never() {
return vec![None];
}
let partition_bys = &self.bound.layout.partition_by;
let order_keys: &[PhysicalSortExpr] = match &self.bound.layout.order_by {
Some(v) => &v[..],
None => &[],
};
let requirement = if self.bound.layout.ordered_partition_by_indices.len()
< partition_bys.len()
{
calc_requirements(partition_bys, order_keys)
} else {
let reordered: Vec<_> = self
.bound
.layout
.ordered_partition_by_indices
.iter()
.map(|idx| Arc::clone(&partition_bys[*idx]))
.collect();
calc_requirements(&reordered, order_keys)
};
vec![requirement]
}
fn input_distribution_requirements(&self) -> InputDistributionRequirements {
if self.can_bypass_ordering_for_never() {
return InputDistributionRequirements::new(vec![
datafusion::physical_plan::Distribution::UnspecifiedDistribution,
]);
}
let keys = self.partition_keys();
let distribution = if keys.is_empty() {
datafusion::physical_plan::Distribution::SinglePartition
} else {
datafusion::physical_plan::Distribution::KeyPartitioned(keys)
};
InputDistributionRequirements::new(vec![distribution])
}
fn maintains_input_order(&self) -> Vec<bool> {
vec![self.bound.layout.maintains_input_order]
}
fn benefits_from_input_partitioning(&self) -> Vec<bool> {
vec![!self.can_bypass_ordering_for_never()]
}
fn metrics(&self) -> Option<MetricsSet> {
Some(self.metrics.clone_inner().with_output_rows_skew())
}
}
fn compute_partition_statistics(
input_stats: &Statistics,
program: &ExecutableMatchProgram,
) -> Statistics {
let output_spec = program.output_spec();
let overlaps = matches!(
program.output_plan().finalizer(),
ExecutableOutputFinalizer::Rows
) && !matches!(
program.after_match_skip(),
ResolvedAfterMatchSkip::PastLastRow
) && program
.compiled_automaton()
.max_match_rows()
.is_none_or(|max_rows| max_rows > 1);
let can_repeat_rows = overlaps
|| program
.output_plan()
.stream()
.emits_navigation_buffer_rows();
let mut column_statistics: Vec<ColumnStatistics> = Vec::new();
for &input_idx in output_spec.passthrough_input_indices() {
let mut column = input_stats
.column_statistics
.get(input_idx)
.cloned()
.unwrap_or_else(ColumnStatistics::new_unknown);
if can_repeat_rows {
column.null_count = Precision::Absent;
column.sum_value = Precision::Absent;
column.byte_size = Precision::Absent;
}
column_statistics.push(column);
}
for _ in output_spec.metadata_columns() {
column_statistics.push(ColumnStatistics::new_unknown());
}
for _ in output_spec.classifier_bitset_symbols() {
column_statistics.push(ColumnStatistics::new_unknown());
}
for _ in 0..program.output_plan().summary_count() {
column_statistics.push(ColumnStatistics::new_unknown());
}
let (num_rows, total_byte_size) = if can_repeat_rows {
(Precision::Absent, Precision::Absent)
} else {
(input_stats.num_rows, input_stats.total_byte_size)
};
Statistics {
num_rows,
total_byte_size,
column_statistics,
}
.to_inexact()
}
impl MatchRecognizePatternExec {
pub fn pre_sort_partition_filter(&self) -> Option<Arc<dyn PartitionMaskExtractor>> {
let program = self.program().as_ref();
let automaton = program.compiled_automaton();
let min_rows = automaton.min_match_rows();
if self.candidate_start_core_rows.is_some()
|| self.bound.layout.partition_by.is_empty()
|| min_rows == 0
|| program.rows_per_match()
== &RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched)
{
return None;
}
let max_rows = (automaton.has_mandatory_start_anchor_prefix()
&& automaton.anchored_at_end())
.then(|| automaton.max_match_rows())
.flatten();
if !program.can_skip_candidate_evaluation
|| program.offset_columns.is_some()
|| program
.classification
.as_ref()
.is_some_and(|c| c.needs_neighbors())
{
return None;
}
BoundedPartitionFilter::wrap(program.pre_sort_filter.clone(), min_rows, max_rows)
}
}
pub fn match_recognize_grouped_order_rule(
emit_order: GroupEmitOrder,
prune_partitions: bool,
) -> HashGroupedOrderRule {
HashGroupedOrderRule::with_consumers(
Default::default(),
vec![Arc::new(MatcherConsumer {
emit_order,
prune_partitions,
})],
)
}
#[derive(Debug)]
struct MatcherConsumer {
emit_order: GroupEmitOrder,
prune_partitions: bool,
}
impl GroupedOrderConsumer for MatcherConsumer {
fn partition_zeros_normalized(&self) -> bool {
true
}
fn match_consumer(&self, node: &dyn ExecutionPlan) -> Option<GroupedOrderTarget> {
let matcher = node.downcast_ref::<MatchRecognizePatternExec>()?;
let layout = &matcher.bound.layout;
let sort = layout.input.downcast_ref::<SortExec>()?;
if matcher.candidate_start_core_rows.is_some()
|| matcher.raw_float_groups
|| !within_key_order(
layout.partition_by.as_slice(),
layout.order_by.as_ref(),
sort.expr().get(layout.partition_by.len()..)?,
)
{
return None;
}
Some(GroupedOrderTarget {
partition_by: layout.partition_by.clone(),
emit_order: self.emit_order,
partition_filter: self
.prune_partitions
.then(|| matcher.pre_sort_partition_filter())
.flatten(),
})
}
}
fn within_key_order(
keys: &[Arc<dyn PhysicalExpr>],
required: Option<&LexOrdering>,
actual: &[PhysicalSortExpr],
) -> bool {
let is_key = |sort: &PhysicalSortExpr| keys.iter().any(|key| key.eq(&sort.expr));
let mut available = actual.iter().filter(|sort| !is_key(sort));
required
.into_iter()
.flat_map(|ordering| ordering.iter())
.filter(|sort| !is_key(sort))
.all(|wanted| available.next() == Some(wanted))
}
fn compatible_group(
group: &HashGroupedOrderExec,
keys: &[Arc<dyn PhysicalExpr>],
order: Option<&LexOrdering>,
) -> bool {
keys.len() == group.output_group_keys().len()
&& group
.output_group_keys()
.iter()
.all(|key| keys.iter().any(|k| k.eq(key)))
&& keys
.iter()
.all(|key| group.output_group_keys().iter().any(|k| k.eq(key)))
&& within_key_order(keys, order, group.output_group_order())
}
impl MatchRecognizePatternExec {
fn grouped_input(&self) -> Option<&HashGroupedOrderExec> {
if self.bound.layout.grouped_input
&& self.candidate_start_core_rows.is_none()
&& !self.raw_float_groups
{
self.bound
.layout
.input
.downcast_ref::<HashGroupedOrderExec>()
} else {
None
}
}
pub(crate) fn uses_unordered_grouped_input(&self) -> bool {
self.grouped_input()
.is_some_and(|group| group.properties().output_ordering().is_none())
}
}
#[cfg(test)]
mod stateful_tests;
#[cfg(test)]
mod tests;