use std::sync::Arc;
use crate::core::vm::{NavigationLayout, RegisterLayout};
use crate::core::{
MatchMetadataColumn, NavigationOffset, NormalizedPattern, StaticPredicateKind,
SymbolEvalMode, SymbolId,
};
use crate::execution::matching::row_loop::row_data::ResolvedRowBindings;
use crate::execution::matching::row_loop::types::PackedNavigationLayout;
use crate::execution::matching::row_loop::vm_scratch::{
BoundStateCell, bind_state_cells,
};
use crate::planning::predicate::VmSourceRef;
use crate::planning::{ManagedAggregateBackend, ManagedAggregateBackendSet};
use datafusion::arrow::datatypes::{DataType, Schema};
use datafusion::common::{DataFusionError, Result};
use datafusion::logical_expr::Volatility;
use datafusion::physical_expr_common::physical_expr::is_volatile;
use crate::execution::deferred::DeferredHistoryProjection;
use crate::execution::matching::program::contracts::{
AggregateProgram, ExecutableSymbolProgramInput, ResolvedStaticExtraction,
ResolvedVmStaticInputs, SymbolProgram, UserSymbolProgram,
validate_dense_aggregate_programs,
};
use crate::execution::matching::program::validated_vm::{
RuntimeVmLayout, ValidatedVmProgram, bind_register_writer, bind_update_program,
symbol_programs_reference_metadata_column,
};
use crate::execution::matching::row_loop::direct_predicate::BoundPredicate;
use crate::execution::matching::{
AggregateHotTables, DefineCachePolicy, ExecutableIncrementalEvaluator,
ExecutableOutputPlan, ExecutableStaticPrecheckProgram, ExecutableSymbolEvaluator,
ExecutableSymbolProgram, ExecutableUserSymbolProgram, PreparedMatcherProgram,
ResolvedAfterMatchSkip, SymbolTable,
};
pub(crate) fn build_static_prechecks(
symbol_count: usize,
bindings: &[ResolvedStaticExtraction],
) -> Vec<ExecutableStaticPrecheckProgram> {
let mut programs = vec![ExecutableStaticPrecheckProgram::default(); symbol_count];
for binding in bindings {
let program = &mut programs[binding.symbol_id.index()];
match binding.kind {
StaticPredicateKind::BooleanAnd => {
program.and_columns.push(binding.column);
}
StaticPredicateKind::BooleanOr => program.or_columns.push(binding.column),
}
}
programs
}
pub(crate) struct ProgramBuilder;
impl ProgramBuilder {
#[expect(
clippy::too_many_arguments,
reason = "one construction boundary for borrowed schema and aggregate programs plus matcher inputs"
)]
pub(crate) fn build(
schema: &Schema,
aggregate_programs: &[AggregateProgram],
normalized_pattern: NormalizedPattern,
max_define_lookahead_rows: NavigationOffset,
has_deferred_history_operations: bool,
output: Arc<ExecutableOutputPlan>,
symbols: ExecutableSymbolProgramInput,
after_match_skip: ResolvedAfterMatchSkip,
) -> Result<PreparedMatcherProgram> {
if !max_define_lookahead_rows.is_zero() && !has_deferred_history_operations {
return Err(DataFusionError::Internal(
"MATCH_RECOGNIZE following-row history requires a Deferred history operation"
.to_string(),
));
}
let ExecutableSymbolProgramInput {
automaton,
relationships,
symbol_columns,
static_extractions,
vm_static_inputs,
symbol_programs,
} = symbols;
let match_aware_symbols: Arc<[SymbolId]> = symbol_programs
.deferred_symbol_ids()
.collect::<Vec<_>>()
.into();
let match_aware_bitmap = match_aware_symbols
.iter()
.filter(|id| id.index() < 64)
.fold(0_u64, |bitmap, id| bitmap | (1 << id.index()));
let (symbol_programs, register_layout) = symbol_programs.into_parts();
validate_dense_aggregate_programs(aggregate_programs)?;
if symbol_programs.len() != automaton.num_symbols() {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE symbol program table has {} slots, expected {} for the compiled automaton",
symbol_programs.len(),
automaton.num_symbols()
)));
}
let has_symbol_qualified_aggregates = aggregate_programs
.iter()
.any(|program| program.symbol_id().is_some());
let has_classifier_aggregates = register_layout.has_classifier_navigation()
|| aggregate_programs
.iter()
.any(AggregateProgram::reads_classifier);
let has_path_dependent_aggregates =
has_symbol_qualified_aggregates || has_classifier_aggregates;
let has_unqualified_aggregates = aggregate_programs
.iter()
.any(|program| program.symbol_id().is_none());
let symbol_name_arrays: Arc<[Option<datafusion::arrow::array::ArrayRef>]> =
automaton
.id_to_symbol()
.iter()
.map(|name| {
name.as_deref().map(|symbol| {
Arc::new(datafusion::arrow::array::StringArray::from(vec![
symbol,
])) as datafusion::arrow::array::ArrayRef
})
})
.collect();
let has_volatile_managed_accumulators =
aggregate_programs.iter().any(|program| {
program.backend() == ManagedAggregateBackend::Accumulator
&& (program.expression().fun().signature().volatility
== Volatility::Volatile
|| program.has_volatile_inputs())
});
let symbol_table = Arc::new(SymbolTable::try_transition_live(
&automaton,
&symbol_columns,
)?);
let aggregate_hot_tables = AggregateHotTables::from_programs(aggregate_programs);
let aggregate_backends = aggregate_programs
.iter()
.map(AggregateProgram::backend)
.collect::<Vec<_>>();
let aggregate_symbols_bitmap =
Self::compute_aggregate_symbols_bitmap(aggregate_programs, &symbol_programs);
let mut path_sensitive_deferred_symbols = None;
let mut deferred_history = DeferredHistoryProjection::default();
for slot in &symbol_programs {
if let SymbolProgram::User(program) = slot
&& program.mode().requires_deferred()
&& !program.deferred_history().is_empty()
{
deferred_history.extend(program.deferred_history());
let bitmap = path_sensitive_deferred_symbols.get_or_insert(0_u64);
if program.id().index() < u64::BITS as usize {
*bitmap |= 1 << program.id().index();
}
}
}
let has_global_match_number_predicate = symbol_programs
.iter()
.filter_map(SymbolProgram::selected_predicate)
.flat_map(|predicate| predicate.sources())
.any(|source| matches!(source, VmSourceRef::MatchNumber))
|| symbol_programs_reference_metadata_column(
schema,
&symbol_programs,
MatchMetadataColumn::MatchNumber,
);
let define_cache = DefineCachePolicy::for_match_start_reuse(
!has_path_dependent_aggregates
&& !has_volatile_managed_accumulators
&& !deferred_history.has_volatile_operations,
);
let static_prechecks =
build_static_prechecks(symbol_programs.len(), &static_extractions);
let aggregate_output_types = aggregate_programs
.iter()
.map(|program| program.output_type().clone())
.collect::<Vec<_>>();
let vm_program = Self::bind_vm(
schema,
symbol_programs,
register_layout,
vm_static_inputs,
&aggregate_output_types,
&aggregate_backends,
define_cache,
static_prechecks,
)?;
Ok(PreparedMatcherProgram {
automaton,
normalized_pattern: Arc::new(normalized_pattern),
output,
after_match_skip,
match_aware_symbols,
match_aware_bitmap,
max_define_lookahead_rows,
has_deferred_history_operations,
has_symbol_qualified_aggregates,
has_classifier_aggregates,
has_unqualified_aggregates,
has_volatile_managed_accumulators,
symbol_table,
symbol_name_arrays,
vm_program,
has_global_match_number_predicate,
aggregate_symbols_bitmap,
path_sensitive_deferred_symbols,
deferred_history,
aggregate_hot_tables,
relationships,
static_extractions,
})
}
#[expect(
clippy::too_many_arguments,
reason = "one physical binding boundary for schema, VM metadata, and evaluator policy"
)]
pub(super) fn bind_vm(
schema: &Schema,
symbol_programs: Vec<SymbolProgram>,
register_layout: RegisterLayout,
static_inputs: ResolvedVmStaticInputs,
aggregate_output_types: &[DataType],
aggregate_backends: &[ManagedAggregateBackend],
define_cache: DefineCachePolicy,
mut static_prechecks: Vec<ExecutableStaticPrecheckProgram>,
) -> Result<ValidatedVmProgram> {
if aggregate_output_types.len() != aggregate_backends.len() {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE aggregate output types and planned backends are not aligned: outputs={}, backends={}",
aggregate_output_types.len(),
aggregate_backends.len()
)));
}
if symbol_programs.first().map(SymbolProgram::register_writers)
!= Some([].as_slice())
{
return datafusion::common::internal_err!(
"MATCH_RECOGNIZE register writers require reserved Empty slot zero"
);
}
register_layout
.validate_symbol_count(symbol_programs.len() - 1)
.map_err(DataFusionError::Internal)?;
let bind_local_excluded = symbol_programs_reference_metadata_column(
schema,
&symbol_programs,
MatchMetadataColumn::Excluded,
);
let mut row_bindings = ResolvedRowBindings::try_new_with_static_inputs(
schema,
®ister_layout,
static_inputs,
)?;
if bind_local_excluded {
row_bindings.resolve_local_excluded(schema)?;
}
let bound_state_cells: Arc<[BoundStateCell]> =
match bind_state_cells(schema, ®ister_layout, aggregate_output_types) {
Ok(cells) => cells.into(),
Err(error) => {
for writer in symbol_programs
.iter()
.flat_map(SymbolProgram::register_writers)
{
bind_register_writer(®ister_layout, &row_bindings, *writer)?;
}
return Err(error);
}
};
ValidatedVmProgram::validate_exact_backend_ownership(
aggregate_backends,
&bound_state_cells,
)?;
let aggregate_backend_set =
ManagedAggregateBackendSet::from_backends(aggregate_backends.iter().copied());
if symbol_programs.len() == 1 && !bound_state_cells.is_empty() {
return datafusion::common::internal_err!(
"MATCH_RECOGNIZE aggregate state requires at least one user symbol"
);
}
let packed_navigation_layout = Arc::new(PackedNavigationLayout::try_new(
register_layout
.navigation_layout()
.unwrap_or(&NavigationLayout::default()),
)?);
let mut bound = Vec::with_capacity(symbol_programs.len());
let mut physical_roots = Vec::new();
for (index, source) in symbol_programs.into_iter().enumerate() {
let program = match source {
SymbolProgram::Empty if index == 0 => ExecutableSymbolProgram::Empty,
SymbolProgram::User(source) if source.id().index() == index => {
let aggregate_state = bind_update_program(
®ister_layout,
&packed_navigation_layout,
&row_bindings,
schema,
&bound_state_cells,
source.register_writers(),
index - 1,
)?;
let direct_predicate = source.selected_predicate().map(|predicate| {
BoundPredicate::bind_direct_predicate(
schema, ®ister_layout, &bound_state_cells, &row_bindings, predicate,
).map_err(|error| DataFusionError::Internal(format!(
"MATCH_RECOGNIZE direct predicate binding failed for symbol id {index}: {error}"
)))
}).transpose()?;
let id = source.id();
let evaluator =
Self::build_symbol_evaluator(source, direct_predicate)?;
evaluator.append_physical_expr_roots(&mut physical_roots);
let symbol_cache = if physical_roots.iter().any(is_volatile) {
DefineCachePolicy::Disabled
} else {
define_cache
};
physical_roots.clear();
ExecutableSymbolProgram::User(ExecutableUserSymbolProgram {
id,
evaluator,
define_cache: symbol_cache,
aggregate_state,
static_prechecks: std::mem::take(&mut static_prechecks[index]),
})
}
_ => {
return datafusion::common::internal_err!(
"MATCH_RECOGNIZE symbol is out of order at dense index {index}"
);
}
};
bound.push(program);
}
Ok(ValidatedVmProgram {
symbol_programs: bound.into(),
runtime_layout: RuntimeVmLayout::from_layout(®ister_layout),
navigation_layout: register_layout.navigation_layout().cloned().map(Arc::new),
packed_navigation_layout,
row_bindings,
bound_state_cells,
aggregate_backend_set,
})
}
fn build_symbol_evaluator(
source: UserSymbolProgram,
direct_predicate: Option<BoundPredicate>,
) -> Result<ExecutableSymbolEvaluator> {
let UserSymbolProgram {
id,
mode,
local_predicate: incremental_define,
hybrid_guard,
..
} = source;
let dense_index = id.index();
match mode {
SymbolEvalMode::Static => Ok(ExecutableSymbolEvaluator::Static),
SymbolEvalMode::Deferred => Ok(ExecutableSymbolEvaluator::History(None)),
SymbolEvalMode::Incremental => {
let source_expr = incremental_define.ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE incremental symbol at dense index {dense_index} has no bound source expression"
))
})?;
Ok(ExecutableSymbolEvaluator::Incremental(
match direct_predicate {
Some(predicate) => ExecutableIncrementalEvaluator::Direct {
predicate,
source_expr,
},
None => {
ExecutableIncrementalEvaluator::Physical { expr: source_expr }
}
},
))
}
SymbolEvalMode::Hybrid => {
let guard = hybrid_guard.ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE Hybrid symbol at dense index {dense_index} has no bound guard"
))
})?;
let source_expr = incremental_define.ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE Hybrid symbol at dense index {dense_index} has a guard but no bound local expression"
))
})?;
Ok(ExecutableSymbolEvaluator::History(Some(
crate::execution::matching::LeadingGuard {
expression: guard,
source_expr,
},
)))
}
}
}
fn compute_aggregate_symbols_bitmap(
aggregate_programs: &[AggregateProgram],
symbol_programs: &[SymbolProgram],
) -> u64 {
let mut aggregate_symbols_bitmap: u64 = 0;
for symbol_id in aggregate_programs
.iter()
.filter_map(AggregateProgram::symbol_id)
{
let sym_id = symbol_id.index();
if sym_id < 64 {
aggregate_symbols_bitmap |= 1 << sym_id;
}
}
for program in symbol_programs {
if let SymbolProgram::User(program) = program
&& program.local_predicate().is_some()
&& program.id().index() < 64
{
aggregate_symbols_bitmap |= 1 << program.id().index();
}
}
log::debug!(
"Computed aggregate_symbols_bitmap: 0b{:064b} ({} symbols use aggregates)",
aggregate_symbols_bitmap,
aggregate_symbols_bitmap.count_ones()
);
aggregate_symbols_bitmap
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::vm::{
AggregateLayout, AggregateValueSource, RegisterLayout, RegisterWriter, SlotInfo,
SlotValueType, VmTier,
};
use crate::core::{
AggregateId, MatchRecognizeOutputSpec, Pattern, RepetitionQuantifier,
RowsPerMatch, Symbol, managed_aggregate_col_name,
};
use crate::execution::matching::predicate_test_helper;
use crate::execution::matching::program::contracts::{
PhysicalHybridGuardExpr, SymbolProgramTable, UserSymbolProgram,
};
use crate::execution::matching::row_loop::compiled_program::{
AggregateHistory, build_exact_aggregate_history,
compact_register_aggregate_history,
};
use crate::execution::matching::{ExecutableOutputPlan, ResolvedInputColumn};
use crate::nfa::CompiledAutomaton;
use crate::planning::predicate::DirectPredicatePlan;
use crate::planning::{AccumulatorInputMode, ManagedAggregateBackend};
use datafusion::arrow::datatypes::{DataType, Field};
use datafusion::functions_aggregate::count::count_udaf;
use datafusion::logical_expr::expr::{AggregateFunction, AggregateFunctionParams};
use datafusion::physical_expr::aggregate::AggregateExprBuilder;
use datafusion::physical_expr::expressions::Literal;
use datafusion::physical_plan::{PhysicalExpr, expressions::Column};
use datafusion::scalar::ScalarValue;
fn true_expr() -> Arc<dyn PhysicalExpr> {
Arc::new(Literal::new(ScalarValue::Boolean(Some(true))))
}
fn evaluator_source(
mode: SymbolEvalMode,
hybrid_guard: Option<PhysicalHybridGuardExpr>,
) -> UserSymbolProgram {
UserSymbolProgram::try_new(
SymbolId::try_new(1, 2).unwrap(),
mode,
mode.uses_incremental().then(true_expr),
hybrid_guard,
vec![],
None,
)
.unwrap()
}
fn static_predicate() -> DirectPredicatePlan {
predicate_test_helper::static_boolean(0, false)
}
fn test_output_program(
schema: &Schema,
automaton: &CompiledAutomaton,
) -> Arc<ExecutableOutputPlan> {
ExecutableOutputPlan::try_rows(
schema,
MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
Arc::from([]),
RowsPerMatch::OneRow,
automaton,
)
.unwrap()
}
fn build_single_symbol_program(
schema: Arc<Schema>,
mode: SymbolEvalMode,
local_predicate: Option<Arc<dyn PhysicalExpr>>,
hybrid_guard: Option<PhysicalHybridGuardExpr>,
predicate: Option<DirectPredicatePlan>,
register_layout: RegisterLayout,
) -> PreparedMatcherProgram {
let normalized_pattern =
NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named("A".to_string())));
let symbols = vec!["A".to_string()];
let automaton =
Arc::new(CompiledAutomaton::compile(&normalized_pattern, &symbols).unwrap());
let runtime_a = SymbolId::try_new(1, automaton.num_symbols()).unwrap();
build_test_program(
schema.as_ref(),
normalized_pattern,
automaton,
vec![
UserSymbolProgram::try_new(
runtime_a,
mode,
local_predicate,
hybrid_guard,
Vec::new(),
predicate,
)
.unwrap(),
],
register_layout,
&[],
)
}
fn build_test_program(
schema: &Schema,
normalized_pattern: NormalizedPattern,
automaton: Arc<CompiledAutomaton>,
programs: Vec<UserSymbolProgram>,
register_layout: RegisterLayout,
aggregate_programs: &[AggregateProgram],
) -> PreparedMatcherProgram {
let symbol_programs =
SymbolProgramTable::try_new(programs, register_layout).unwrap();
let (required_predicates, required_scalars) =
symbol_programs.required_static_input_prefixes();
assert_eq!(required_scalars, 0);
let vm_static_inputs = ResolvedVmStaticInputs::try_new_for_selected_predicates(
vec![
crate::execution::matching::ResolvedBoolColumn::new_validated(0);
required_predicates
],
Vec::new(),
required_predicates,
required_scalars,
)
.unwrap();
let match_aware_symbols =
symbol_programs.deferred_symbol_ids().collect::<Vec<_>>();
let symbol_columns = crate::execution::matching::test_symbol_columns(
automaton.as_ref(),
&match_aware_symbols,
schema,
symbol_programs.test_local_predicate_ids().as_slice(),
)
.unwrap();
let resolved_output = test_output_program(schema, &automaton);
ProgramBuilder::build(
schema,
aggregate_programs,
normalized_pattern,
NavigationOffset::ZERO,
false,
resolved_output,
ExecutableSymbolProgramInput {
automaton,
relationships: Default::default(),
symbol_columns,
static_extractions: vec![],
vm_static_inputs,
symbol_programs,
},
ResolvedAfterMatchSkip::PastLastRow,
)
.unwrap()
}
fn build_with_optional_predicate(
mode: SymbolEvalMode,
hybrid_guard: Option<PhysicalHybridGuardExpr>,
predicate: Option<DirectPredicatePlan>,
register_layout: RegisterLayout,
) -> PreparedMatcherProgram {
let schema = Arc::new(Schema::new(vec![
Field::new("flag", DataType::Boolean, true),
Field::new("__mr_symbol_a", DataType::Boolean, false),
]));
let local_predicate =
matches!(mode, SymbolEvalMode::Incremental | SymbolEvalMode::Hybrid)
.then(true_expr);
build_single_symbol_program(
schema,
mode,
local_predicate,
hybrid_guard,
predicate,
register_layout,
)
}
fn repeated_permute_history_pattern_with(
bounded: bool,
) -> (NormalizedPattern, CompiledAutomaton) {
let named = |name: &str| Symbol::Named(name.to_string());
let quantifier = if bounded {
RepetitionQuantifier::Exactly(2)
} else {
RepetitionQuantifier::OneOrMore
};
let normalized_pattern = NormalizedPattern::Ast(Pattern::Concat(vec![
Pattern::Repetition(
Box::new(Pattern::Permute(vec![named("A"), named("B"), named("C")])),
quantifier,
),
Pattern::Symbol(named("D")),
]));
let symbols = ["A", "B", "C", "D"]
.into_iter()
.map(str::to_string)
.collect::<Vec<_>>();
let automaton =
CompiledAutomaton::compile(&normalized_pattern, &symbols).unwrap();
(normalized_pattern, automaton)
}
fn build_repeated_permute_count_program(
backend: ManagedAggregateBackend,
tier: VmTier,
mode: SymbolEvalMode,
bounded: bool,
include_unqualified: bool,
input: Option<Arc<dyn PhysicalExpr>>,
counts_every_row: bool,
) -> PreparedMatcherProgram {
let (normalized_pattern, automaton) =
repeated_permute_history_pattern_with(bounded);
let automaton = Arc::new(automaton);
let symbols = ["A", "B", "C", "D"].map(str::to_string);
let aggregate_count = if include_unqualified { 2 } else { 1 };
let mut fields = vec![Field::new("id", DataType::Int64, false)];
fields.extend(symbols.iter().map(|name| {
Field::new(crate::core::symbol_col_name(name), DataType::Boolean, false)
}));
fields.extend((0..aggregate_count).map(|index| {
Field::new(managed_aggregate_col_name(index), DataType::Int64, false)
}));
let schema = Arc::new(Schema::new(fields));
let count = count_udaf();
let input = input.unwrap_or_else(|| Arc::new(Column::new("id", 0)));
let aggregate_programs = (0..aggregate_count)
.map(|index| {
let expression = Arc::new(
AggregateExprBuilder::new(
Arc::clone(&count),
vec![Arc::clone(&input)],
)
.schema(Arc::clone(&schema))
.alias(managed_aggregate_col_name(index))
.build()
.unwrap(),
);
let function = AggregateFunction {
func: Arc::clone(&count),
params: AggregateFunctionParams {
args: vec![],
distinct: false,
filter: None,
order_by: vec![],
null_treatment: None,
},
};
AggregateProgram::try_new(
AggregateId::try_new(index, aggregate_count).unwrap(),
expression,
function,
backend,
AccumulatorInputMode::Batch,
counts_every_row,
ResolvedInputColumn::new_validated(symbols.len() + 1 + index),
(index == 0)
.then(|| SymbolId::try_new(1, automaton.num_symbols()).unwrap()),
schema.as_ref(),
)
.unwrap()
})
.collect::<Vec<_>>();
assert_eq!(
aggregate_programs[0].has_volatile_inputs(),
is_volatile(&input)
);
let aggregates = (0..aggregate_count)
.map(|index| match backend {
ManagedAggregateBackend::Registers => AggregateLayout {
slot: Some(SlotInfo::new(index, SlotValueType::Int64, 0)),
value_source: AggregateValueSource::Register { slot: index },
..Default::default()
},
ManagedAggregateBackend::Accumulator => AggregateLayout::default(),
})
.collect();
let register_count = if backend == ManagedAggregateBackend::Registers {
aggregate_count
} else {
0
};
let layout = RegisterLayout::builder(register_count, aggregates)
.vm_tier(tier)
.try_build()
.unwrap();
let local_predicate =
matches!(mode, SymbolEvalMode::Incremental | SymbolEvalMode::Hybrid)
.then(true_expr);
let programs = (0..symbols.len())
.map(|user_index| {
let update_ops = if backend == ManagedAggregateBackend::Registers {
(0..aggregate_count)
.filter(|index| *index != 0 || user_index == 0)
.map(|index| RegisterWriter::Count {
aggregate: index,
input: None,
})
.collect()
} else {
Vec::new()
};
UserSymbolProgram::try_new(
SymbolId::try_new(user_index + 1, automaton.num_symbols()).unwrap(),
if user_index == 0 {
mode
} else {
SymbolEvalMode::Static
},
(user_index == 0).then(|| local_predicate.clone()).flatten(),
None,
update_ops,
None,
)
.unwrap()
})
.collect();
build_test_program(
schema.as_ref(),
normalized_pattern,
automaton,
programs,
layout,
&aggregate_programs,
)
}
#[test]
fn sealed_program_controls_history_template_elision() {
use ManagedAggregateBackend::{Accumulator, Registers};
use SymbolEvalMode::{Deferred, Incremental};
use VmTier::{Compact, Standard};
for (backend, tier, mode) in [
(Registers, Standard, Incremental),
(Accumulator, Compact, Incremental),
(Registers, Compact, Deferred),
] {
for unqualified in [false, true] {
let program = build_repeated_permute_count_program(
backend,
tier,
mode,
true,
unqualified,
None,
true,
);
let history =
build_exact_aggregate_history(&program, program.automaton.as_ref());
assert!(
history.empty_position_tracking().is_some(),
"{backend:?}/{tier:?}/{mode:?}"
);
assert_eq!(history.empty_labeled_tracking().is_some(), unqualified);
}
}
for (bounded, offset_only) in [(true, false), (false, true)] {
let program = build_repeated_permute_count_program(
Registers,
Compact,
Incremental,
bounded,
false,
None,
true,
);
let history =
build_exact_aggregate_history(&program, program.automaton.as_ref());
assert!(matches!(
(offset_only, history),
(false, AggregateHistory::None) | (true, AggregateHistory::OffsetOnly)
));
}
#[cfg(target_pointer_width = "64")]
assert!(matches!(
compact_register_aggregate_history(Some(u32::MAX as usize + 1)),
AggregateHistory::OffsetOnly
));
}
#[test]
fn selected_evaluators_expose_only_their_required_sources() {
use crate::execution::matching::program::validated_vm::ExecutableEvaluatorKernel::{Static, Typed, Unsupported};
use SymbolEvalMode::{Deferred, Hybrid, Incremental};
for (make_predicate, static_input) in [
(
predicate_test_helper::positive_match_number
as fn() -> DirectPredicatePlan,
false,
),
(static_predicate as fn() -> DirectPredicatePlan, true),
] {
for (mode, guard, has_predicate, kernel, roots) in [
(SymbolEvalMode::Static, None, false, Static, 0),
(Deferred, None, false, Unsupported, 0),
(
Hybrid,
Some(PhysicalHybridGuardExpr::Unknown),
false,
Unsupported,
0,
),
(Incremental, None, false, Unsupported, 1),
(Incremental, None, true, Typed, 0),
(
Hybrid,
Some(PhysicalHybridGuardExpr::Unknown),
true,
Unsupported,
0,
),
] {
if static_input && !has_predicate {
continue;
}
let layout = RegisterLayout::default();
let program = build_with_optional_predicate(
mode,
guard,
has_predicate.then(make_predicate),
layout,
);
let evaluator = program.vm_program.symbol_programs()[1]
.user()
.unwrap()
.evaluator();
assert!(matches!(
(mode, evaluator),
(SymbolEvalMode::Static, ExecutableSymbolEvaluator::Static)
| (Deferred, ExecutableSymbolEvaluator::History(None))
| (Incremental, ExecutableSymbolEvaluator::Incremental(_))
| (Hybrid, ExecutableSymbolEvaluator::History(Some(_)))
));
assert_eq!(evaluator.kernel(), kernel);
assert_eq!(evaluator.may_read_history(), mode.requires_deferred());
assert_eq!(
evaluator.has_bound_source(),
evaluator.source_expr().is_some()
);
assert_eq!(
program.has_global_match_number_predicate,
kernel == Typed && !static_input
);
assert_eq!(
!program
.vm_program
.row_bindings()
.static_predicate_columns
.is_empty(),
kernel == Typed && static_input
);
let mut actual_roots = Vec::new();
evaluator.append_physical_expr_roots(&mut actual_roots);
assert_eq!(actual_roots.len(), roots);
if !has_predicate && mode == Incremental {
assert!(matches!(
evaluator,
ExecutableSymbolEvaluator::Incremental(
ExecutableIncrementalEvaluator::Physical { .. }
)
));
}
}
}
}
#[test]
fn physical_fallback_and_hybrid_guard_detect_match_number_predicates() {
use datafusion::logical_expr::Operator;
use datafusion::physical_expr::expressions::{BinaryExpr, CastExpr};
let make_schema = |match_number_name: &str| {
Arc::new(Schema::new(vec![
Field::new("flag", DataType::Boolean, true),
Field::new("__mr_symbol_a", DataType::Boolean, false),
Field::new(match_number_name, DataType::Int64, true),
]))
};
let cast_match_number = |name: &str| -> Arc<dyn PhysicalExpr> {
Arc::new(BinaryExpr::new(
Arc::new(CastExpr::new(
Arc::new(Column::new(name, 2)),
DataType::Utf8,
None,
)),
Operator::Eq,
Arc::new(Literal::new(ScalarValue::Utf8(Some("1".into())))),
))
};
let bitwise_match_number = |name: &str| -> Arc<dyn PhysicalExpr> {
Arc::new(BinaryExpr::new(
Arc::new(BinaryExpr::new(
Arc::new(Column::new(name, 2)),
Operator::BitwiseAnd,
Arc::new(Literal::new(ScalarValue::Int64(Some(1)))),
)),
Operator::Eq,
Arc::new(Literal::new(ScalarValue::Int64(Some(1)))),
))
};
let canonical = MatchMetadataColumn::MatchNumber.as_ref();
for (label, schema_col, mode, local, guard, expected) in [
(
"incremental physical cast match_number",
canonical,
SymbolEvalMode::Incremental,
cast_match_number(canonical),
None,
true,
),
(
"incremental physical bitwise match_number (case-insensitive schema)",
"__MR_MATCH_NUMBER",
SymbolEvalMode::Incremental,
bitwise_match_number("__MR_MATCH_NUMBER"),
None,
true,
),
(
"hybrid guard match_number",
canonical,
SymbolEvalMode::Hybrid,
true_expr(),
Some(PhysicalHybridGuardExpr::And(
Box::new(PhysicalHybridGuardExpr::Local(cast_match_number(
canonical,
))),
Box::new(PhysicalHybridGuardExpr::Unknown),
)),
true,
),
(
"incremental physical without match_number reference",
canonical,
SymbolEvalMode::Incremental,
true_expr(),
None,
false,
),
(
"hybrid guard without match_number reference",
canonical,
SymbolEvalMode::Hybrid,
true_expr(),
Some(PhysicalHybridGuardExpr::Unknown),
false,
),
] {
let program = build_single_symbol_program(
make_schema(schema_col),
mode,
Some(local),
guard,
None,
RegisterLayout::default(),
);
assert_eq!(
program.has_global_match_number_predicate, expected,
"{label}"
);
if mode == SymbolEvalMode::Incremental {
assert!(
matches!(
program.vm_program.symbol_programs()[1]
.user()
.unwrap()
.evaluator(),
ExecutableSymbolEvaluator::Incremental(
ExecutableIncrementalEvaluator::Physical { .. }
)
),
"{label}: expected Physical fallback evaluator"
);
}
}
}
#[test]
fn nested_hybrid_guard_roots_preserve_leaf_identity_and_order() {
let first: Arc<dyn PhysicalExpr> =
Arc::new(Literal::new(ScalarValue::Boolean(Some(true))));
let second: Arc<dyn PhysicalExpr> =
Arc::new(Literal::new(ScalarValue::Boolean(Some(false))));
let guard = PhysicalHybridGuardExpr::And(
Box::new(PhysicalHybridGuardExpr::Local(Arc::clone(&first))),
Box::new(PhysicalHybridGuardExpr::Or(
Box::new(PhysicalHybridGuardExpr::Unknown),
Box::new(PhysicalHybridGuardExpr::Not(Box::new(
PhysicalHybridGuardExpr::Local(Arc::clone(&second)),
))),
)),
);
let hybrid = ProgramBuilder::build_symbol_evaluator(
evaluator_source(SymbolEvalMode::Hybrid, Some(guard)),
None,
)
.unwrap();
let mut roots = Vec::new();
hybrid.append_physical_expr_roots(&mut roots);
assert_eq!(roots.len(), 2, "only local Hybrid guard leaves are roots");
assert!(Arc::ptr_eq(&roots[0], &first));
assert!(Arc::ptr_eq(&roots[1], &second));
}
#[test]
fn volatile_aggregate_inputs_mark_managed_accumulators_volatile() {
use datafusion::common::DFSchema;
use datafusion::logical_expr::{
col, create_udf, physical_planning_context::PhysicalPlanningContext,
};
use datafusion::physical_expr::{
create_physical_expr, execution_props::ExecutionProps,
};
let df_schema = DFSchema::try_from(Schema::new(vec![Field::new(
"id",
DataType::Int64,
false,
)]))
.unwrap();
let volatile_udf = create_udf(
"volatile_arg",
vec![DataType::Int64],
DataType::Int64,
Volatility::Volatile,
Arc::new(|args| Ok(args[0].clone())),
);
let volatile_input = create_physical_expr(
&volatile_udf.call(vec![col("id")]),
&df_schema,
&ExecutionProps::new(),
&PhysicalPlanningContext::default(),
)
.unwrap();
let immutable_input: Arc<dyn PhysicalExpr> = Arc::new(Column::new("id", 0));
for (input, expect_volatile) in [(immutable_input, false), (volatile_input, true)]
{
assert_eq!(is_volatile(&input), expect_volatile);
let prepared = build_repeated_permute_count_program(
ManagedAggregateBackend::Accumulator,
VmTier::Compact,
SymbolEvalMode::Incremental,
true,
false,
Some(input),
false,
);
assert_eq!(prepared.has_volatile_managed_accumulators, expect_volatile);
let history =
build_exact_aggregate_history(&prepared, prepared.automaton.as_ref());
if expect_volatile {
assert!(matches!(history, AggregateHistory::OffsetOnly));
} else {
assert!(history.empty_position_tracking().is_some());
}
}
}
}