use std::sync::Arc;
#[cfg(test)]
use std::sync::atomic::AtomicBool;
use crate::config::MatchRecognizeConfig;
use crate::core::{NormalizedPattern, RowsPerMatch, SymbolId};
use crate::execution::classification::PackedAnchors;
use crate::execution::deferred::DeferredEvaluatorFactory;
use crate::execution::deferred::DeferredHistoryProjection;
use crate::execution::identity::{ExecutionPartitionId, MatchProgramId};
use crate::execution::metrics::PatternMetrics;
use crate::execution::physical::virtual_input::VirtualInputMapping;
use crate::nfa::{AutomatonStateId, CompiledAutomaton, PatternCompileLimits};
use crate::planning::{ManagedAggregateBackend, ManagedAggregateBackendSet};
use datafusion::arrow::datatypes::DataType;
use datafusion_common::Result;
use datafusion_physical_expr::aggregate::AggregateFunctionExpr;
use smallvec::SmallVec;
use super::aggregate_runtime::ManagedAccumulatorEvaluator;
#[cfg(test)]
use super::bindings::SymbolTable;
use super::bindings::{ResolvedAfterMatchSkip, ResolvedBoolColumn, ResolvedInputColumn};
use super::collection;
use super::pattern_optimization;
use super::program::contracts::AggregateProgram;
use super::program::validated_vm::{RuntimeVmLayout, ValidatedVmProgram};
use super::program::{ExecutableMatchProgram, PreparedMatcherProgram};
use super::row_loop;
use super::row_loop::compiled_program::ExecutablePatternVariant;
#[cfg(test)]
use super::symbol_program::ExecutableSymbolProgram;
#[derive(Debug, Clone)]
pub(crate) struct MatcherConfiguration {
pub runtime_absent_symbol_pruning_disabled: bool,
pub compact_paths_disabled: bool,
pub cancellation_poll_interval: usize,
pub execution_deadline_millis: usize,
pub single_row_array_cache_max_entries: usize,
pub single_row_array_cache_max_bytes: usize,
pub max_prev_offset: usize,
pub pattern_compile_limits: PatternCompileLimits,
}
fn aggregate_value_supports_data_type(data_type: &DataType) -> bool {
matches!(
data_type,
DataType::Int8
| DataType::Int16
| DataType::Int32
| DataType::Int64
| DataType::UInt8
| DataType::UInt16
| DataType::UInt32
| DataType::UInt64
| DataType::Float32
| DataType::Float64
| DataType::Decimal128(_, _)
| DataType::Decimal256(_, _)
| DataType::Boolean
| DataType::Null
)
}
pub(crate) struct MatcherProgram {
pub(crate) virtual_input: Option<Arc<VirtualInputMapping>>,
pub(crate) packed_lane_column: Option<usize>,
pub(crate) required_packed_mask: u64,
pub(crate) required_static_symbol_indices: SmallVec<[usize; 8]>,
pub(crate) required_and_precheck_columns: SmallVec<[ResolvedBoolColumn; 8]>,
pub(crate) classification:
Option<Arc<crate::execution::classification::MatchAwareClassification>>,
pub(crate) packed_anchors: Option<Arc<PackedAnchors>>,
can_skip_candidate_evaluation: bool,
history_factory: Option<Arc<DeferredEvaluatorFactory>>,
pub(super) prepared: Arc<PreparedMatcherProgram>,
base_variant: Arc<ExecutablePatternVariant>,
pub(super) config: MatcherConfiguration,
program_id: MatchProgramId,
aggregate_programs: Arc<[AggregateProgram]>,
supports_value_equivalence: bool,
requires_primitive_values: bool,
}
fn compute_required_static_precheck(
variant: &ExecutablePatternVariant,
) -> (u64, SmallVec<[usize; 8]>, SmallVec<[ResolvedBoolColumn; 8]>) {
let automaton = variant.automaton();
let required = automaton.required_symbols_mask();
if required == 0 || automaton.min_match_rows() == 0 {
return (0, SmallVec::new(), SmallVec::new());
}
let symbols = variant.symbol_execution_plan();
let symbol_programs = variant.symbol_programs();
let mut and_guarded_mask = 0u64;
let mut static_indices = SmallVec::<[usize; 8]>::new();
let mut and_precheck_columns = SmallVec::<[ResolvedBoolColumn; 8]>::new();
let mut rem = required;
while rem != 0 {
let bit_idx = rem.trailing_zeros() as usize;
rem &= rem - 1;
let sym_idx = bit_idx + 1;
if sym_idx < u64::BITS as usize && (symbols.eager_bitmap & (1u64 << sym_idx)) == 0
{
static_indices.push(sym_idx);
}
}
for &id in symbols.static_precheck_ids() {
let index = id.index();
if index < u64::BITS as usize
&& let Some(user) = symbol_programs[index].user()
&& !user.static_predicate_and_columns().is_empty()
&& user.static_predicate_or_columns().is_empty()
{
and_guarded_mask |= 1u64 << index;
if index >= 1 && (required & (1u64 << (index - 1))) != 0 {
and_precheck_columns
.extend_from_slice(user.static_predicate_and_columns());
}
}
}
let required_packed_mask =
(required << 1) & (!symbols.eager_bitmap | and_guarded_mask);
(required_packed_mask, static_indices, and_precheck_columns)
}
impl MatcherProgram {
fn new(executable: &ExecutableMatchProgram, config: MatcherConfiguration) -> Self {
let has_qualified_count_accumulator =
executable.aggregate_programs.iter().any(|program| {
program.backend() == ManagedAggregateBackend::Accumulator
&& program.counts_every_row()
&& (program.symbol_id().is_some() || program.reads_classifier())
});
let supports_value_equivalence =
!executable.prepared.has_volatile_managed_accumulators
&& !executable.prepared.deferred_history.has_volatile_operations
&& executable.aggregate_programs.iter().all(|program| {
program.backend() != ManagedAggregateBackend::Accumulator
|| program.counts_every_row()
|| (program.symbol_id().is_none() && !program.reads_classifier())
})
&& (!has_qualified_count_accumulator
|| executable.aggregate_programs.iter().all(|program| {
aggregate_value_supports_data_type(program.output_type())
}));
let requires_primitive_values = has_qualified_count_accumulator;
let base_variant = executable.base_variant.configured(&config);
let (
required_packed_mask,
required_static_symbol_indices,
required_and_precheck_columns,
) = compute_required_static_precheck(base_variant.as_ref());
Self {
virtual_input: executable.virtual_input.clone(),
classification: executable.classification.clone(),
packed_lane_column: executable
.classification
.as_ref()
.and_then(|c| c.lane_column),
required_packed_mask,
required_static_symbol_indices,
required_and_precheck_columns,
packed_anchors: if config.runtime_absent_symbol_pruning_disabled {
None
} else {
executable.packed_anchors.clone()
},
can_skip_candidate_evaluation: executable.can_skip_candidate_evaluation,
history_factory: executable.deferred_evaluator_factory.clone(),
prepared: Arc::clone(&executable.prepared),
base_variant,
config,
program_id: executable.program_id(),
aggregate_programs: Arc::clone(&executable.aggregate_programs),
supports_value_equivalence,
requires_primitive_values,
}
}
pub(super) fn new_candidate_history(
&self,
memory: &datafusion_execution::memory_pool::MemoryReservation,
) -> Result<crate::execution::deferred::CandidateHistory> {
let factory = self.history_factory.as_ref().ok_or_else(|| {
datafusion_common::internal_datafusion_err!(
"History predicate has no bound evaluator"
)
})?;
factory.candidate_history(memory)
}
#[inline]
pub(crate) fn base_variant(&self) -> &Arc<ExecutablePatternVariant> {
&self.base_variant
}
#[inline]
pub(crate) fn automaton_arc(&self) -> Arc<CompiledAutomaton> {
self.base_variant.automaton_arc()
}
#[inline]
pub(crate) fn automaton(&self) -> &CompiledAutomaton {
self.base_variant.automaton()
}
#[inline]
pub(crate) fn vm_program(&self) -> &ValidatedVmProgram {
&self.prepared.vm_program
}
#[inline]
pub(crate) fn config(&self) -> &MatcherConfiguration {
&self.config
}
#[inline]
pub(crate) const fn program_id(&self) -> MatchProgramId {
self.program_id
}
#[inline]
pub(crate) fn aggregate_programs(&self) -> &Arc<[AggregateProgram]> {
&self.aggregate_programs
}
#[inline]
pub(crate) fn aggregate_hot_tables(&self) -> &AggregateHotTables {
&self.prepared.aggregate_hot_tables
}
#[inline]
pub(crate) fn normalized_pattern(&self) -> &NormalizedPattern {
self.prepared.normalized_pattern()
}
#[inline]
pub(crate) fn rows_per_match(&self) -> &RowsPerMatch {
self.prepared.rows_per_match()
}
#[inline]
pub(crate) fn after_match_skip(&self) -> &ResolvedAfterMatchSkip {
self.prepared.after_match_skip()
}
#[inline]
pub(crate) fn match_aware_symbols(&self) -> &[SymbolId] {
self.prepared.match_aware_symbols()
}
#[inline]
pub(crate) fn match_aware_bitmap(&self) -> u64 {
self.prepared.match_aware_bitmap
}
#[inline]
#[cfg(test)]
pub(crate) fn has_lookahead_defines(&self) -> bool {
self.prepared.has_lookahead_defines()
}
#[inline]
#[cfg(test)]
pub(crate) fn has_symbol_qualified_aggregates(&self) -> bool {
self.prepared.has_symbol_qualified_aggregates
}
#[inline]
pub(crate) fn has_path_dependent_aggregates(&self) -> bool {
self.prepared.has_path_dependent_aggregates()
}
#[inline]
pub(crate) fn symbol_name_arrays(
&self,
) -> &[Option<datafusion::arrow::array::ArrayRef>] {
&self.prepared.symbol_name_arrays
}
#[inline]
pub(crate) fn aggregate_symbols_bitmap(&self) -> u64 {
self.prepared.aggregate_symbols_bitmap
}
#[inline]
pub(crate) fn has_reachable_path_sensitive_deferred(
&self,
compiled: &CompiledAutomaton,
state_id: AutomatonStateId,
) -> bool {
self.prepared
.path_sensitive_deferred_symbols
.is_some_and(|symbols| {
!compiled.nfa().state(state_id).is_accepting()
&& compiled.has_reachable_symbols(state_id, symbols)
})
}
#[inline]
pub(crate) const fn can_skip_candidate_evaluation(&self) -> bool {
self.can_skip_candidate_evaluation
}
#[inline]
pub(crate) const fn supports_value_equivalence(&self) -> bool {
self.supports_value_equivalence
}
#[inline]
pub(crate) const fn state_supports_value_equivalence(
&self,
has_primitive_values: bool,
) -> bool {
self.supports_value_equivalence
&& (!self.requires_primitive_values || has_primitive_values)
}
pub(crate) fn deferred_history(&self) -> &DeferredHistoryProjection {
&self.prepared.deferred_history
}
}
#[derive(Clone)]
pub(crate) struct AggregateHotTables {
pub(crate) evaluator: ManagedAccumulatorEvaluator,
pub(crate) factories: Arc<[Arc<AggregateFunctionExpr>]>,
pub(crate) columns: Arc<[ResolvedInputColumn]>,
}
impl AggregateHotTables {
pub(super) fn from_programs(programs: &[AggregateProgram]) -> Self {
Self {
evaluator: ManagedAccumulatorEvaluator::new(programs.iter()),
factories: programs
.iter()
.map(|program| Arc::clone(program.expression()))
.collect::<Vec<_>>()
.into(),
columns: programs
.iter()
.map(AggregateProgram::column)
.collect::<Vec<_>>()
.into(),
}
}
}
pub(crate) struct MatcherServices {
pub(super) anchors: collection::AnchorWindows,
pub(crate) metrics: Option<Box<PatternMetrics>>,
pub(crate) absent_symbol_cache: pattern_optimization::AbsentSymbolCache,
#[cfg(test)]
pub(crate) abort_signal: Option<Arc<AtomicBool>>,
pub(crate) selected_output_buffer: Option<collection::SelectedOutputBuffer>,
}
pub struct PatternMatcher {
pub(crate) program: MatcherProgram,
pub(crate) services: MatcherServices,
pub(super) execution_partition_id: ExecutionPartitionId,
#[cfg(test)]
force_generic_scan: bool,
}
impl PatternMatcher {
#[cfg(test)]
pub(crate) fn seal_variant(
&self,
automaton: Arc<CompiledAutomaton>,
active_symbol_columns: Arc<SymbolTable>,
) -> Result<Arc<ExecutablePatternVariant>> {
self.seal_variant_for_pattern(
self.program.normalized_pattern(),
automaton,
active_symbol_columns,
)
}
#[cfg(test)]
pub(crate) fn seal_variant_for_pattern(
&self,
normalized_pattern: &NormalizedPattern,
automaton: Arc<CompiledAutomaton>,
active_symbol_columns: Arc<SymbolTable>,
) -> Result<Arc<ExecutablePatternVariant>> {
ExecutablePatternVariant::try_new(
self.program.prepared.as_ref(),
normalized_pattern,
automaton,
active_symbol_columns,
self.program.config().compact_paths_disabled,
)
}
#[inline]
#[cfg(test)]
pub(crate) fn symbol_programs(&self) -> &[ExecutableSymbolProgram] {
self.program.vm_program().symbol_programs()
}
#[inline]
pub(crate) fn runtime_vm_layout(&self) -> &RuntimeVmLayout {
self.program.vm_program().runtime_layout()
}
pub(crate) fn bound_input_slots(&self) -> Vec<usize> {
let mut slots = Vec::new();
self.program
.vm_program()
.visit_bound_input_columns(|column| slots.push(column));
slots.extend(
self.row_bindings()
.static_predicate_columns
.iter()
.map(|c| c.index()),
);
slots.sort_unstable();
slots.dedup();
slots
}
#[inline]
pub(crate) fn row_bindings(&self) -> &row_loop::row_data::ResolvedRowBindings {
self.program.vm_program().row_bindings()
}
#[inline]
pub(crate) fn bound_state_cells(&self) -> &[row_loop::vm_scratch::BoundStateCell] {
self.program.vm_program().bound_state_cells()
}
fn build_matcher_config(
match_config: &MatchRecognizeConfig,
max_prev_offset: usize,
) -> MatcherConfiguration {
MatcherConfiguration {
runtime_absent_symbol_pruning_disabled: match_config
.diagnostics
.disable_pattern_optimizer,
compact_paths_disabled: match_config.diagnostics.disable_compact_paths,
cancellation_poll_interval: match_config.limits.cancellation_poll_interval,
execution_deadline_millis: match_config.limits.execution_deadline_millis,
single_row_array_cache_max_entries: match_config
.limits
.single_row_array_cache_max_entries,
single_row_array_cache_max_bytes: match_config
.limits
.single_row_array_cache_max_bytes,
max_prev_offset,
pattern_compile_limits: match_config.limits.pattern_compile_limits(),
}
}
pub(crate) fn from_executable(
executable: &ExecutableMatchProgram,
config: &MatchRecognizeConfig,
) -> Self {
let matcher_config = Self::build_matcher_config(
config,
executable
.output_spec()
.navigation_offsets()
.previous()
.as_usize(),
);
let program = MatcherProgram::new(executable, matcher_config);
Self {
program,
services: MatcherServices {
anchors: Default::default(),
metrics: None,
absent_symbol_cache: pattern_optimization::AbsentSymbolCache::new(),
#[cfg(test)]
abort_signal: None,
selected_output_buffer: None,
},
execution_partition_id: ExecutionPartitionId::new(0),
#[cfg(test)]
force_generic_scan: false,
}
}
pub(crate) fn with_metrics(mut self, pm: &PatternMetrics) -> Self {
self.services.metrics = Some(Box::new(pm.clone()));
self
}
pub(crate) fn with_execution_partition_id(
mut self,
execution_partition_id: ExecutionPartitionId,
) -> Self {
self.execution_partition_id = execution_partition_id;
self
}
pub(crate) fn program_id(&self) -> MatchProgramId {
self.program.program_id()
}
#[cfg(test)]
pub(crate) fn execution_binding(&self) -> row_loop::state::ExecutionBinding {
row_loop::state::ExecutionBinding {
execution_partition_id: self.execution_partition_id,
program_id: self.program_id(),
}
}
#[cfg(test)]
pub(crate) fn with_abort_signal(mut self, signal: Arc<AtomicBool>) -> Self {
self.services.abort_signal = Some(signal);
self
}
#[cfg(test)]
pub(crate) fn force_generic_scan_for_test(&mut self, force: bool) {
self.force_generic_scan = force;
}
#[cfg(test)]
pub(crate) fn perturb_poisoned_retry_settings_for_test(&mut self) {
let config = &mut self.program.config;
config.single_row_array_cache_max_entries =
usize::from(config.single_row_array_cache_max_entries == 0);
config.cancellation_poll_interval = if config.cancellation_poll_interval == 1 {
2
} else {
1
};
}
#[cfg(test)]
pub(crate) fn install_malformed_aggregate_factories_for_test(
&mut self,
factories: Arc<[Arc<AggregateFunctionExpr>]>,
) {
Arc::make_mut(&mut self.program.prepared)
.aggregate_hot_tables
.factories = factories;
}
#[cfg(test)]
pub(crate) const fn generic_scan_forced_by_control(&self) -> bool {
self.force_generic_scan
}
#[inline]
pub(crate) fn is_aborted(&self) -> bool {
#[cfg(test)]
{
self.services
.abort_signal
.as_ref()
.is_some_and(|signal| signal.load(std::sync::atomic::Ordering::Relaxed))
}
#[cfg(not(test))]
false
}
#[inline]
pub(crate) fn aggregate_backend_set(&self) -> ManagedAggregateBackendSet {
self.program.vm_program().aggregate_backend_set()
}
#[inline]
#[cfg(test)]
pub(crate) fn has_managed_aggregates(&self) -> bool {
self.aggregate_backend_set() != ManagedAggregateBackendSet::Empty
}
#[inline]
pub(crate) fn automaton_arc(&self) -> Arc<CompiledAutomaton> {
self.program.automaton_arc()
}
#[inline]
pub(crate) fn automaton(&self) -> &CompiledAutomaton {
self.program.automaton()
}
}