pub(crate) mod contracts;
pub(crate) mod validated_vm;
use std::sync::Arc;
use crate::core::{
MatchRecognizeOutputSpec, NavigationOffset, NormalizedPattern, RowsPerMatch,
SymbolEvalMode, SymbolId,
};
use crate::nfa::CompiledAutomaton;
use crate::planning::SymbolRelationships;
use datafusion::arrow::datatypes::SchemaRef;
use datafusion::physical_plan::PhysicalExpr;
use datafusion_common::Result;
pub(super) mod build;
use super::row_loop::lane_scan::LaneRejection;
use super::{
AggregateHotTables, ExecutableOutputPlan, ExecutablePatternVariant,
ExecutableSymbolProgram, ExecutableUserSymbolProgram, ResolvedAfterMatchSkip,
SymbolTable,
};
use crate::execution::classification::OffsetColumns;
use crate::execution::classification::{MatchAwareClassification, PackedAnchors};
use crate::execution::deferred::DeferredEvaluatorFactory;
use crate::execution::deferred::DeferredHistoryProjection;
use crate::execution::identity::MatchProgramId;
use crate::execution::physical::virtual_input::VirtualInputMapping;
use build::ProgramBuilder;
use contracts::{
AggregateProgram, ExecutableMatchProgramInput, ResolvedStaticExtraction,
};
use validated_vm::{RuntimeVmLayout, ValidatedVmProgram};
#[derive(Clone)]
pub(crate) struct ExecutableMatchProgram {
pub(crate) virtual_input: Option<Arc<VirtualInputMapping>>,
pub(crate) offset_columns: Option<Arc<OffsetColumns>>,
pub(crate) pre_sort_filter:
Option<Arc<dyn datafusion_hash_grouped_order::PartitionMaskExtractor>>,
pub(crate) classification: Option<Arc<MatchAwareClassification>>,
pub(crate) packed_anchors: Option<Arc<PackedAnchors>>,
pub(crate) can_skip_candidate_evaluation: bool,
pub(crate) non_overlapping_starts: bool,
program_id: MatchProgramId,
pub(crate) input_schema: SchemaRef,
pub(super) aggregate_programs: Arc<[AggregateProgram]>,
pub(super) deferred_evaluator_factory: Option<Arc<DeferredEvaluatorFactory>>,
pub(super) base_variant: Arc<ExecutablePatternVariant>,
pub(super) prepared: Arc<PreparedMatcherProgram>,
}
impl std::fmt::Debug for ExecutableMatchProgram {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ExecutableMatchProgram")
.field("symbols", &self.prepared.vm_program.symbol_programs().len())
.field("aggregates", &self.aggregate_programs.len())
.field("output_schema", self.output_plan().schema())
.finish()
}
}
impl ExecutableMatchProgram {
pub(crate) fn rows_per_match(&self) -> &RowsPerMatch {
self.output_plan().rows_per_match()
}
pub(crate) fn with_synthetic_row_filter(
&self,
rows: RowsPerMatch,
suppress_terminal_empty: bool,
) -> Result<Self> {
self.with_filtered_output(
Arc::clone(self.output_plan())
.with_synthetic_row_filter(rows, suppress_terminal_empty)?,
)
}
pub(crate) fn with_extended_input_schema(&self, schema: &SchemaRef) -> Result<Self> {
let mut cloned = self.clone_with_fresh_identity()?;
cloned.input_schema = Arc::clone(schema);
Ok(cloned)
}
pub(crate) fn is_infallible_never(&self) -> bool {
matches!(self.normalized_pattern(), NormalizedPattern::Never)
&& self.can_skip_candidate_evaluation
&& self.offset_columns.is_none()
&& self
.classification
.as_ref()
.is_none_or(|c| !c.needs_neighbors())
}
pub(crate) fn emits_ordered_unmatched(&self) -> bool {
matches!(
self.rows_per_match(),
RowsPerMatch::AllRows(crate::core::EmptyMatchesMode::WithUnmatched)
) && matches!(self.after_match_skip(), ResolvedAfterMatchSkip::PastLastRow)
&& !self.output_plan().stream().emits_navigation_buffer_rows()
&& self.compiled_automaton().min_match_rows() > 0
&& !self.stream_requirements().interleaves_logical_partitions
}
pub(crate) fn referenced_input_columns(&self, width: usize) -> Vec<bool> {
if !self.can_skip_candidate_evaluation
|| self.offset_columns.is_some()
|| self
.user_symbol_programs()
.any(|s| s.evaluator().mode() != SymbolEvalMode::Static)
|| !self.aggregate_programs.is_empty()
{
return vec![true; width];
}
let mut needed = vec![false; width];
self.output_plan()
.mark_referenced_input_columns(&mut needed);
if self.is_infallible_never() {
return needed;
}
let absorbed = self
.classification
.as_ref()
.map(|c| {
c.classifier.mark_referenced_input_columns(&mut needed);
c.predicates
.iter()
.map(|p| p.output)
.collect::<std::collections::HashSet<_>>()
})
.unwrap_or_default();
for symbol in self.base_variant().active_symbol_columns().columns() {
if !absorbed.contains(&symbol.column.index())
&& let Some(slot) = needed.get_mut(symbol.column.index())
{
*slot = true;
}
}
needed
}
pub(crate) fn try_new(input: ExecutableMatchProgramInput) -> Result<Self> {
let ExecutableMatchProgramInput {
input_schema,
normalized_pattern,
max_define_lookahead_rows,
has_deferred_history_operations,
symbols,
aggregate_programs,
output,
after_match_skip,
deferred_evaluator_factory,
} = input;
let aggregate_programs: Arc<[AggregateProgram]> = aggregate_programs.into();
let prepared = ProgramBuilder::build(
input_schema.as_ref(),
aggregate_programs.as_ref(),
normalized_pattern,
max_define_lookahead_rows,
has_deferred_history_operations,
Arc::clone(&output),
symbols,
after_match_skip,
)?;
let base_variant = ExecutablePatternVariant::try_new(
&prepared,
prepared.normalized_pattern(),
Arc::clone(&prepared.automaton),
Arc::clone(&prepared.symbol_table),
false,
)?;
let can_skip_candidate_evaluation = aggregate_programs.is_empty()
&& deferred_evaluator_factory.is_none()
&& !prepared.has_deferred_history_operations
&& prepared
.vm_program
.symbol_programs()
.iter()
.filter_map(ExecutableSymbolProgram::user)
.all(|program| program.evaluator().mode() == SymbolEvalMode::Static);
let non_overlapping_starts = can_skip_candidate_evaluation
&& matches!(
prepared.after_match_skip(),
ResolvedAfterMatchSkip::PastLastRow
)
&& prepared
.automaton
.max_match_rows()
.is_some_and(|rows| rows > 1)
&& super::graph::non_overlap::proves_non_overlapping_starts(
&prepared.automaton,
&prepared.relationships,
)?;
Ok(Self {
non_overlapping_starts,
virtual_input: None,
offset_columns: None,
pre_sort_filter: None,
classification: None,
packed_anchors: None,
can_skip_candidate_evaluation,
program_id: MatchProgramId::try_allocate()?,
input_schema,
aggregate_programs,
deferred_evaluator_factory,
base_variant,
prepared: Arc::new(prepared),
})
}
pub(crate) fn compiled_automaton(&self) -> &Arc<CompiledAutomaton> {
&self.prepared.automaton
}
pub(crate) fn normalized_pattern(&self) -> &NormalizedPattern {
self.prepared.normalized_pattern()
}
pub(crate) fn after_match_skip(&self) -> &ResolvedAfterMatchSkip {
self.prepared.after_match_skip()
}
pub(crate) fn match_aware_symbols(&self) -> &[SymbolId] {
self.prepared.match_aware_symbols()
}
#[cfg(test)]
pub(crate) fn has_lookahead_defines(&self) -> bool {
self.prepared.has_lookahead_defines()
}
#[cfg(test)]
pub(crate) fn max_define_lookahead_rows(&self) -> NavigationOffset {
self.prepared.max_define_lookahead_rows
}
pub(crate) fn has_deferred_history_operations(&self) -> bool {
self.prepared.has_deferred_history_operations
}
pub(crate) fn has_global_match_number_predicate(&self) -> bool {
self.prepared.has_global_match_number_predicate
}
pub(crate) const fn program_id(&self) -> MatchProgramId {
self.program_id
}
pub(crate) fn output_schema(&self) -> &SchemaRef {
self.output_plan().schema()
}
pub(crate) fn output_spec(&self) -> &MatchRecognizeOutputSpec {
self.output_plan().spec()
}
pub(crate) fn output_plan(&self) -> &Arc<ExecutableOutputPlan> {
self.prepared.output_plan()
}
pub(crate) fn clone_with_fresh_identity(&self) -> Result<Self> {
let mut cloned = self.clone();
cloned.program_id = MatchProgramId::try_allocate()?;
Ok(cloned)
}
pub(crate) fn with_filtered_output(
&self,
output: Arc<ExecutableOutputPlan>,
) -> Result<Self> {
let mut cloned = self.clone_with_fresh_identity()?;
Arc::make_mut(&mut cloned.prepared).output = output;
Ok(cloned)
}
pub(crate) fn with_appended_passthrough(
&self,
input_schema: &SchemaRef,
input_index: usize,
) -> Result<Self> {
let output = self.output_plan().with_appended_passthrough(
input_schema.as_ref(),
input_index,
self.compiled_automaton().as_ref(),
)?;
let mut cloned = self.with_filtered_output(output)?;
cloned.input_schema = Arc::clone(input_schema);
Ok(cloned)
}
pub(crate) fn aggregate_programs(&self) -> &[AggregateProgram] {
&self.aggregate_programs
}
pub(crate) fn base_variant(&self) -> &Arc<ExecutablePatternVariant> {
&self.base_variant
}
pub(crate) fn static_extractions(&self) -> &[ResolvedStaticExtraction] {
&self.prepared.static_extractions
}
pub(crate) fn history_input_ordinals(&self) -> &[usize] {
self.deferred_evaluator_factory
.as_ref()
.map_or(&[], |f| f.input_ordinals())
}
pub(crate) fn has_deferred_evaluator_factory(&self) -> bool {
self.deferred_evaluator_factory.is_some()
}
pub(crate) fn physical_expr_roots(&self) -> Vec<Arc<dyn PhysicalExpr>> {
let mut roots = Vec::new();
for program in self.user_symbol_programs() {
program.evaluator().append_physical_expr_roots(&mut roots);
}
for aggregate in self.aggregate_programs() {
roots.extend_from_slice(aggregate.input_expressions());
}
if let Some(factory) = &self.deferred_evaluator_factory {
roots.extend(factory.physical_expr_roots());
}
roots
}
#[cfg(test)]
pub(crate) fn symbol_eval_modes(&self) -> Vec<SymbolEvalMode> {
self.prepared
.vm_program
.symbol_programs()
.iter()
.map(ExecutableSymbolProgram::mode)
.collect()
}
pub(crate) fn user_symbol_programs(
&self,
) -> impl Iterator<Item = &ExecutableUserSymbolProgram> {
self.prepared
.vm_program
.symbol_programs()
.iter()
.filter_map(ExecutableSymbolProgram::user)
}
pub(crate) fn runtime_vm_layout(&self) -> &RuntimeVmLayout {
self.prepared.vm_program.runtime_layout()
}
pub(crate) fn vm_program(&self) -> &ValidatedVmProgram {
&self.prepared.vm_program
}
pub(crate) fn explain_lane_rejection(&self) -> Option<LaneRejection> {
self.base_variant.lane_outcome().rejection()
}
}
#[derive(Clone)]
pub(crate) struct PreparedMatcherProgram {
pub(crate) automaton: Arc<CompiledAutomaton>,
pub(crate) normalized_pattern: Arc<NormalizedPattern>,
pub(crate) output: Arc<ExecutableOutputPlan>,
pub(crate) after_match_skip: ResolvedAfterMatchSkip,
pub(crate) match_aware_symbols: Arc<[SymbolId]>,
pub(crate) match_aware_bitmap: u64,
pub(crate) max_define_lookahead_rows: NavigationOffset,
pub(crate) has_deferred_history_operations: bool,
pub(crate) has_symbol_qualified_aggregates: bool,
pub(crate) has_classifier_aggregates: bool,
pub(crate) has_unqualified_aggregates: bool,
pub(crate) has_volatile_managed_accumulators: bool,
pub(crate) symbol_table: Arc<SymbolTable>,
pub(crate) symbol_name_arrays: Arc<[Option<datafusion::arrow::array::ArrayRef>]>,
pub(crate) vm_program: ValidatedVmProgram,
pub(crate) has_global_match_number_predicate: bool,
pub(crate) aggregate_symbols_bitmap: u64,
pub(crate) path_sensitive_deferred_symbols: Option<u64>,
pub(crate) deferred_history: DeferredHistoryProjection,
pub(crate) aggregate_hot_tables: AggregateHotTables,
pub(crate) relationships: SymbolRelationships,
pub(crate) static_extractions: Vec<ResolvedStaticExtraction>,
}
impl PreparedMatcherProgram {
#[inline]
pub(crate) fn normalized_pattern(&self) -> &NormalizedPattern {
self.normalized_pattern.as_ref()
}
#[inline]
pub(crate) fn output_plan(&self) -> &Arc<ExecutableOutputPlan> {
&self.output
}
#[inline]
pub(crate) fn rows_per_match(&self) -> &RowsPerMatch {
self.output.rows_per_match()
}
#[inline]
pub(crate) fn after_match_skip(&self) -> &ResolvedAfterMatchSkip {
&self.after_match_skip
}
#[inline]
pub(crate) fn match_aware_symbols(&self) -> &[SymbolId] {
&self.match_aware_symbols
}
#[inline]
pub(crate) const fn has_lookahead_defines(&self) -> bool {
!self.max_define_lookahead_rows.is_zero()
}
#[inline]
pub(crate) const fn has_path_dependent_aggregates(&self) -> bool {
self.has_symbol_qualified_aggregates || self.has_classifier_aggregates
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct StreamRequirements {
pub(crate) independent_candidate_starts: bool,
pub(crate) needs_complete_partition: bool,
pub(crate) interleaves_logical_partitions: bool,
}