use crate::core::vm::RegisterWriter;
use crate::core::{MatchMetadataColumn, classifier_bits_col_name};
use crate::planning::deferred_program::{
DeferredOperationSpec, DeferredProgramSpec, compile_deferred_program,
};
use crate::planning::expr_safety::{
can_discard_scalar, can_precompute, scalar_ordering_type_is_safe,
scalar_value_type_is_safe,
};
use crate::planning::hybrid_guard::LogicalHybridGuardExpr;
use crate::planning::logical::{
ExtractionKind, InternalSlotOwner, LogicalMatchProgram, LogicalSymbol,
};
use crate::planning::predicate::{
VmCompileContext, VmManagedPredicateColumn, VmMetadataComparisonColumn,
VmPredicateInputColumn, VmPredicateInputRole, compile_direct_predicate,
vm_type_from_data_type,
};
use crate::planning::vm_assembly::{
AggregateAssembly, AssembledMatchVm, VmAssemblyDowngrade, assemble_match_vm_state,
build_aggregate_assemblies,
};
use crate::planning::{
ManagedAggregateBackend, MatchCompilerOptions, RoutedEvaluator, RoutedHistoryGuard,
RoutedMatchProgram, RoutedPredicate, RoutedSymbol,
};
use datafusion::arrow::datatypes::DataType;
use datafusion::common::{DFSchema, DataFusionError, Result, internal_err};
use datafusion::logical_expr::expr::WindowFunction;
use datafusion::logical_expr::type_coercion::functions::fields_with_udf;
use datafusion::logical_expr::{
AggregateUDF, Expr, ExprSchemable, Volatility, WindowFunctionDefinition,
};
use std::collections::{BTreeMap, BTreeSet};
fn deferred_aggregate_is_infallible(
udaf: &AggregateUDF,
window: &WindowFunction,
result_type: &DataType,
history_schema: &DFSchema,
) -> bool {
if udaf.signature().volatility != Volatility::Immutable || window.params.distinct {
return false;
}
let Ok(arg_fields) = window
.params
.args
.iter()
.map(|arg| arg.to_field(history_schema).map(|(_, field)| field))
.collect::<Result<Vec<_>>>()
else {
return false;
};
let Ok(coerced_fields) = fields_with_udf(&arg_fields, udaf) else {
return false;
};
if coerced_fields.len() != arg_fields.len()
|| !arg_fields
.iter()
.zip(&coerced_fields)
.all(|(source, target)| source.data_type() == target.data_type())
{
return false;
}
if udaf == datafusion::functions_aggregate::count::count_udaf().as_ref() {
return true;
}
if arg_fields.len() != 1 {
return false;
}
if udaf == datafusion::functions_aggregate::sum::sum_udaf().as_ref() {
return matches!(
result_type,
DataType::Int64 | DataType::UInt64 | DataType::Float64
);
}
if udaf == datafusion::functions_aggregate::average::avg_udaf().as_ref() {
return *result_type == DataType::Float64;
}
if udaf == datafusion::functions_aggregate::min_max::min_udaf().as_ref()
|| udaf == datafusion::functions_aggregate::min_max::max_udaf().as_ref()
{
return arg_fields[0].data_type() == result_type
&& !result_type.is_null()
&& scalar_ordering_type_is_safe(result_type);
}
if udaf == datafusion::functions_aggregate::bool_and_or::bool_and_udaf().as_ref()
|| udaf == datafusion::functions_aggregate::bool_and_or::bool_or_udaf().as_ref()
{
return *result_type == DataType::Boolean;
}
if udaf == datafusion_functions_aggregate::first_last::first_value_udaf().as_ref()
|| udaf == datafusion_functions_aggregate::first_last::last_value_udaf().as_ref()
{
return arg_fields[0].data_type() == result_type
&& scalar_value_type_is_safe(result_type)
&& window.params.order_by.iter().all(|sort| {
sort.expr
.get_type(history_schema)
.is_ok_and(|data_type| scalar_ordering_type_is_safe(&data_type))
});
}
false
}
fn deferred_operation_is_safe(
operation: &DeferredOperationSpec,
history_schema: &DFSchema,
) -> bool {
let Expr::WindowFunction(window) = operation.expr() else {
return false;
};
let WindowFunctionDefinition::AggregateUDF(udaf) = &window.fun else {
return false;
};
if operation.expr().is_volatile()
|| !deferred_aggregate_is_infallible(
udaf.as_ref(),
window.as_ref(),
operation.result_field().data_type(),
history_schema,
)
{
return false;
}
let safe_scalar = |expr: &Expr| can_discard_scalar(expr, Some(history_schema));
window.params.args.iter().all(safe_scalar)
&& window.params.filter.as_deref().is_none_or(|filter| {
safe_scalar(filter)
&& matches!(filter.get_type(history_schema), Ok(DataType::Boolean))
})
&& window
.params
.order_by
.iter()
.all(|sort| safe_scalar(&sort.expr))
}
fn deferred_predicate_is_safe(
predicate: &crate::planning::deferred_program::DeferredPredicateSpec,
deferred: &DeferredProgramSpec,
) -> bool {
if !can_discard_scalar(
predicate.expr(),
Some(deferred.predicate_input_schema().as_ref()),
) {
return false;
}
let history_schema = deferred.history_schema().as_ref();
predicate.extra_ordinals().iter().all(|&index| {
history_schema
.fields()
.get(index)
.is_some_and(|field| scalar_value_type_is_safe(field.data_type()))
}) && predicate.operation_indices().iter().all(|&index| {
deferred_operation_is_safe(&deferred.operations()[index], history_schema)
})
}
fn route_symbol(
logical: &LogicalSymbol,
writers: Vec<RegisterWriter>,
context: &VmCompileContext,
input_schema: &DFSchema,
deferred: Option<&DeferredProgramSpec>,
) -> RoutedSymbol {
let predicate = logical.predicate();
let local = logical.demanded_expr().or_else(|| predicate.local_expr());
let routed_predicate = local
.map(|expr| {
compile_direct_predicate(expr, context)
.map(RoutedPredicate::Direct)
.unwrap_or_else(RoutedPredicate::Rejected)
})
.unwrap_or(RoutedPredicate::NotApplicable);
let hybrid_guard = predicate.hybrid_guard().filter(|_| {
let local_safe = local.is_some_and(|expr| {
!expr.is_volatile() && can_precompute(expr, input_schema)
});
local_safe
&& deferred.is_some_and(|deferred| {
deferred.predicates()[logical.id().index()]
.as_ref()
.is_some_and(|predicate| {
deferred_predicate_is_safe(predicate, deferred)
})
})
});
let evaluator = if predicate.deferred_expr().is_some() {
RoutedEvaluator::History {
local_guard: local.cloned().map(|source| RoutedHistoryGuard {
source,
expression: hybrid_guard
.cloned()
.unwrap_or(LogicalHybridGuardExpr::Unknown),
}),
}
} else if let Some(local) = local {
RoutedEvaluator::Local(local.clone())
} else {
RoutedEvaluator::Static
};
RoutedSymbol::new(logical.id(), evaluator, writers, routed_predicate)
}
fn vm_predicate_inputs(
program: &LogicalMatchProgram,
input_schema: &DFSchema,
) -> Result<Vec<VmPredicateInputColumn>> {
let mut claimed_names = BTreeSet::new();
let mut inputs = Vec::new();
let mut next_static_predicate_idx = 0;
let mut next_static_scalar_idx = 0;
for requirement in program.matcher_input_slots() {
let owner = requirement.owner();
let name = program.internal_slot_name(owner).ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE routed compiler has no name for matcher slot {owner:?}"
))
})?;
claimed_names.insert(name.clone());
let role = match owner {
InternalSlotOwner::ManagedAggregate(_)
| InternalSlotOwner::SymbolResult(_) => continue,
InternalSlotOwner::StaticExtraction(id) => {
match program.static_extractions()[id.index()].kind() {
ExtractionKind::BooleanAnd | ExtractionKind::BooleanOr => {
let bool_idx = next_static_predicate_idx;
next_static_predicate_idx += 1;
VmPredicateInputRole::StaticPredicate { bool_idx }
}
ExtractionKind::Scalar => {
let scalar_idx = next_static_scalar_idx;
next_static_scalar_idx += 1;
VmPredicateInputRole::StaticScalar { scalar_idx }
}
}
}
};
inputs.push(VmPredicateInputColumn::new(
name,
vm_type_from_data_type(requirement.data_type(), requirement.nullable()),
role,
));
}
claimed_names.extend(
MatchMetadataColumn::all()
.into_iter()
.map(|metadata| metadata.as_ref().to_string()),
);
for (metadata, role) in [
(
MatchMetadataColumn::MatchNumber,
VmMetadataComparisonColumn::MatchNumber,
),
(
MatchMetadataColumn::MatchSequenceNumber,
VmMetadataComparisonColumn::MatchSequenceNumber,
),
] {
let name = metadata.as_ref().to_string();
inputs.push(VmPredicateInputColumn::new(
name,
vm_type_from_data_type(&metadata.data_type(), metadata.is_nullable()),
VmPredicateInputRole::Metadata(role),
));
}
for symbol in program.symbols() {
let name = classifier_bits_col_name(symbol.name());
claimed_names.insert(name.clone());
inputs.push(VmPredicateInputColumn::new(
name,
vm_type_from_data_type(&DataType::Boolean, true),
VmPredicateInputRole::Classifier,
));
}
let mut row_name_counts = BTreeMap::new();
for field in input_schema.fields() {
*row_name_counts.entry(field.name().as_str()).or_insert(0) += 1;
}
for field in input_schema.fields() {
if claimed_names.insert(field.name().clone()) {
let ty = if row_name_counts[field.name().as_str()] == 1 {
vm_type_from_data_type(field.data_type(), field.is_nullable())
} else {
None
};
inputs.push(VmPredicateInputColumn::new(
field.name().to_string(),
ty,
VmPredicateInputRole::RowValue,
));
}
}
Ok(inputs)
}
pub fn compile_match_program(
program: &LogicalMatchProgram,
input_schema: &DFSchema,
options: MatchCompilerOptions,
) -> Result<RoutedMatchProgram> {
let input_columns = vm_predicate_inputs(program, input_schema)?;
let context = predicate_compile_context(program, &input_columns)?;
let deferred = compile_deferred_program(program, input_schema)?;
let mut aggregates = build_aggregate_assemblies(program, input_schema, options);
let outcome = assemble_match_vm_state(program, &aggregates, input_schema);
let (assembly, downgrade_reason) =
cohere_match_vm_state(program.symbols().len(), &mut aggregates, outcome);
let AssembledMatchVm {
register_writers,
register_layout,
} = assembly;
if register_writers.len() != program.symbols().len() {
return internal_err!(
"MATCH_RECOGNIZE routed symbol tables are misaligned: logical={}, state={}",
program.symbols().len(),
register_writers.len()
);
}
let symbols = program
.symbols()
.iter()
.zip(register_writers)
.map(|(symbol, writers)| {
route_symbol(symbol, writers, &context, input_schema, deferred.as_ref())
})
.collect();
let aggregates = aggregates
.into_iter()
.map(AggregateAssembly::into_routed)
.collect();
RoutedMatchProgram::try_new(
symbols,
aggregates,
register_layout,
downgrade_reason,
deferred,
)
}
fn cohere_match_vm_state(
symbol_count: usize,
aggregates: &mut [AggregateAssembly],
outcome: Result<AssembledMatchVm, VmAssemblyDowngrade>,
) -> (AssembledMatchVm, Option<VmAssemblyDowngrade>) {
match outcome {
Ok(assembly) => (assembly, None),
Err(reason) => {
for aggregate in aggregates.iter_mut() {
aggregate.backend = ManagedAggregateBackend::Accumulator;
}
log::warn!(
"MATCH_RECOGNIZE VM assembly downgraded register aggregates: {reason:?}"
);
(
AssembledMatchVm::empty(symbol_count, aggregates.len()),
Some(reason),
)
}
}
}
fn predicate_compile_context(
program: &LogicalMatchProgram,
input_columns: &[VmPredicateInputColumn],
) -> Result<VmCompileContext> {
VmCompileContext::try_new(
managed_predicate_columns(program)?,
input_columns.to_vec(),
Default::default(),
)
.map_err(|error| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE predicate inputs failed validation: {error:?}"
))
})
}
fn managed_predicate_columns(
program: &LogicalMatchProgram,
) -> Result<Vec<VmManagedPredicateColumn>> {
let aggregates = program.managed_aggregates();
let mut columns = vec![None; aggregates.len()];
for requirement in program.matcher_input_slots() {
let InternalSlotOwner::ManagedAggregate(id) = requirement.owner() else {
continue;
};
let index = id.index();
let Some(aggregate) = aggregates
.get(index)
.filter(|aggregate| aggregate.id() == id)
else {
return internal_err!(
"MATCH_RECOGNIZE managed predicate slot {index} has no dense aggregate owner"
);
};
if columns[index].is_some() {
return internal_err!(
"MATCH_RECOGNIZE managed predicate slot {index} is declared more than once"
);
}
columns[index] = Some(VmManagedPredicateColumn::new(
index,
aggregate.column_name(),
vm_type_from_data_type(requirement.data_type(), requirement.nullable())
.map(|ty| ty.scalar),
));
}
columns
.into_iter()
.enumerate()
.map(|(index, column)| {
column.ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE managed aggregate {index} has no predicate input slot"
))
})
})
.collect()
}
#[cfg(test)]
mod match_vm_plan_tests {
use std::sync::Arc;
use crate::core::vm::{AggregateLayout, MAX_REGISTERS, RegisterLayout, VmTier};
use crate::core::{
AfterMatchSkip, MatchRecognizeOutputSpec, Pattern, RowsPerMatch, Symbol,
classifier_bits_col_name,
};
use datafusion::arrow::datatypes::{DataType, Field, Schema, UnionFields, UnionMode};
use datafusion::common::{DFSchema, Result, ScalarValue};
use datafusion::functions_aggregate::array_agg::array_agg_udaf;
use datafusion::functions_aggregate::average::avg_udaf;
use datafusion::functions_aggregate::count::{count, count_udaf};
use datafusion::functions_aggregate::min_max::{max_udaf, min_udaf};
use datafusion::functions_aggregate::sum::{sum, sum_udaf};
use datafusion::logical_expr::expr::{Cast, WindowFunction};
use datafusion::logical_expr::{
EmptyRelation, Expr, LogicalPlan, WindowFunctionDefinition, col, lit,
};
use datafusion_functions_aggregate::first_last::{first_value_udaf, last_value_udaf};
use super::{
AggregateAssembly, AssembledMatchVm, LogicalHybridGuardExpr,
ManagedAggregateBackend, MatchCompilerOptions, RoutedMatchProgram,
VmAssemblyDowngrade, build_aggregate_assemblies, cohere_match_vm_state,
compile_match_program, deferred_aggregate_is_infallible,
};
use crate::planning::logical::{
LogicalMatchOutput, LogicalMatchProgram, LogicalMatchProgramInput,
LogicalSymbolInput, ManagedAggregateInput, MatchRecognize,
};
fn mixed_aggregates() -> Vec<AggregateAssembly> {
let Expr::AggregateFunction(count) = count(lit(1_i64)) else {
unreachable!()
};
let program = LogicalMatchProgram::try_new(LogicalMatchProgramInput {
partition_by: vec![],
order_by: vec![],
after_skip: AfterMatchSkip::PastLastRow,
pattern: Pattern::Symbol(Symbol::Named("A".into())),
symbols: vec![LogicalSymbolInput::static_("A", lit(true))],
match_aware: crate::planning::logical::ExecutableMatchProgramInput::new(
vec![],
vec![
ManagedAggregateInput::new(count.clone(), None),
ManagedAggregateInput::new(count, None),
],
),
output: LogicalMatchOutput::rows(
RowsPerMatch::OneRow,
MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
),
symbol_relationships: Default::default(),
})
.unwrap();
let mut aggregates = build_aggregate_assemblies(
&program,
&DFSchema::empty(),
MatchCompilerOptions::default(),
);
aggregates[1].backend = ManagedAggregateBackend::Accumulator;
aggregates
}
#[test]
fn assembly_failure_atomically_downgrades_all_register_routes() {
let mut aggregates = mixed_aggregates();
let reason = VmAssemblyDowngrade::RegisterCapacity {
aggregate_id: 0,
used: MAX_REGISTERS,
required: 1,
capacity: MAX_REGISTERS,
};
let (assembly, downgrade_reason) =
cohere_match_vm_state(2, &mut aggregates, Err(reason.clone()));
let AssembledMatchVm {
register_writers: symbols,
register_layout: layout,
} = assembly;
assert!(aggregates.iter().all(|aggregate| {
aggregate.backend == ManagedAggregateBackend::Accumulator
}));
assert_eq!(downgrade_reason, Some(reason));
assert!(symbols.iter().all(Vec::is_empty));
assert_eq!(layout.vm_tier(), VmTier::Compact);
assert_eq!(
layout.aggregates(),
vec![AggregateLayout::default(); aggregates.len()]
);
}
#[test]
fn mixed_accumulator_and_standard_navigation_preserves_register_routes() {
let mut aggregates = mixed_aggregates();
let assembly = AssembledMatchVm {
register_writers: vec![Vec::new(); 2],
register_layout: RegisterLayout::builder(
0,
vec![AggregateLayout::default(); aggregates.len()],
)
.vm_tier(VmTier::Standard)
.try_build()
.unwrap(),
};
let (assembly, downgrade_reason) =
cohere_match_vm_state(2, &mut aggregates, Ok(assembly));
assert_eq!(aggregates[0].backend, ManagedAggregateBackend::Registers);
assert_eq!(aggregates[1].backend, ManagedAggregateBackend::Accumulator);
assert_eq!(downgrade_reason, None);
let AssembledMatchVm {
register_writers: symbols,
register_layout: layout,
} = assembly;
assert_eq!(layout.vm_tier(), VmTier::Standard);
assert!(symbols.iter().all(Vec::is_empty));
assert_eq!(
layout.aggregates(),
vec![AggregateLayout::default(); aggregates.len()]
);
}
fn compile_hybrid_b_routed_with_schema(
extra_fields: Vec<Field>,
a_deferred: Expr,
b_deferred: Expr,
options: MatchCompilerOptions,
) -> Result<RoutedMatchProgram> {
let mut fields = vec![
Field::new("ord", DataType::Int64, false),
Field::new("x", DataType::Int64, false),
Field::new("__mr_managed_agg_0", DataType::Int64, true),
];
fields.extend(extra_fields);
let input_schema = Arc::new(DFSchema::try_from(Schema::new(fields))?);
let input = LogicalPlan::EmptyRelation(EmptyRelation {
produce_one_row: false,
schema: Arc::clone(&input_schema),
});
let Expr::AggregateFunction(sum_x) = sum(col("x")) else {
unreachable!()
};
let b_local = col("__mr_managed_agg_0")
.gt(lit(0_i64))
.or(col("ord").eq(lit(2_i64)));
let node = MatchRecognize::try_new(
input,
LogicalMatchProgramInput {
partition_by: vec![],
order_by: vec![],
after_skip: AfterMatchSkip::PastLastRow,
pattern: Pattern::Concat(vec![
Pattern::Symbol(Symbol::Named("A".into())),
Pattern::Symbol(Symbol::Named("B".into())),
]),
symbols: vec![
LogicalSymbolInput::deferred("A", a_deferred),
LogicalSymbolInput::hybrid("B", b_local, b_deferred),
],
match_aware: crate::planning::logical::ExecutableMatchProgramInput::new(
vec![],
vec![ManagedAggregateInput::new(sum_x, Some("A".into()))],
),
output: LogicalMatchOutput::rows(
RowsPerMatch::OneRow,
MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
),
symbol_relationships: Default::default(),
},
)?;
compile_match_program(node.program(), input_schema.as_ref(), options)
}
fn compile_hybrid_b_guard_with_schema(
extra_fields: Vec<Field>,
a_deferred: Expr,
b_deferred: Expr,
) -> Result<LogicalHybridGuardExpr> {
let routed = compile_hybrid_b_routed_with_schema(
extra_fields,
a_deferred,
b_deferred,
MatchCompilerOptions::default(),
)?;
Ok(routed.symbols()[1]
.evaluator()
.hybrid_guard()
.expect("B must retain Hybrid route")
.clone())
}
fn safe_a_deferred() -> Expr {
Expr::WindowFunction(Box::new(WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(sum_udaf()),
vec![col("x")],
)))
.gt(lit(0_i64))
}
fn compile_hybrid_b_guard(b_deferred: Expr) -> Result<LogicalHybridGuardExpr> {
compile_hybrid_b_guard_with_schema(vec![], safe_a_deferred(), b_deferred)
}
#[test]
fn hybrid_guard_checks_shared_deferred_operation_safety() -> Result<()> {
let random = || datafusion::functions::math::random().call(vec![]);
let a_mask = || col(classifier_bits_col_name("A"));
let agg_window =
|udaf, arg: Expr, filter: Option<Expr>, order_by: Option<Expr>| {
let mut window = WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(udaf),
vec![arg],
);
window.params.filter = filter.map(Box::new);
if let Some(sort) = order_by {
window.params.order_by = vec![sort.sort(true, true)];
}
Expr::WindowFunction(Box::new(window))
};
let sum_window = |arg: Expr, filter: Option<Expr>, order_by: Option<Expr>| {
agg_window(sum_udaf(), arg, filter, order_by)
};
let expected_active = LogicalHybridGuardExpr::Or(
Box::new(LogicalHybridGuardExpr::Unknown),
Box::new(LogicalHybridGuardExpr::Local(col("ord").eq(lit(2_i64)))),
);
let safe_b = sum_window(col("x"), Some(a_mask()), None)
.gt(lit(0_i64))
.or(col("ord").eq(lit(2_i64)));
assert_eq!(compile_hybrid_b_guard(safe_b.clone())?, expected_active);
let fallible_a = sum_window(lit(10_i64) / col("x"), None, None).gt(lit(0_i64));
assert_eq!(
compile_hybrid_b_guard_with_schema(vec![], fallible_a, safe_b)?,
expected_active,
"unreferenced fallible deferred operation must preserve Hybrid guard"
);
let coerced_avg_b = agg_window(
avg_udaf(),
Expr::Cast(Cast::new(Box::new(col("x")), DataType::Float64)),
Some(a_mask()),
None,
)
.gt(lit(0.0_f64))
.or(col("ord").eq(lit(2_i64)));
assert_eq!(compile_hybrid_b_guard(coerced_avg_b)?, expected_active);
let uncoerced_avg_b = agg_window(avg_udaf(), col("x"), Some(a_mask()), None)
.gt(lit(0.0_f64))
.or(col("ord").eq(lit(2_i64)));
let array_agg_b = agg_window(array_agg_udaf(), col("x"), None, None)
.is_not_null()
.or(col("ord").eq(lit(2_i64)));
for (label, unsafe_b) in [
(
"fallible arg",
sum_window(lit(10_i64) / col("x"), Some(a_mask()), None)
.gt(lit(0_i64))
.or(col("ord").eq(lit(2_i64))),
),
(
"fallible filter",
sum_window(
col("x"),
Some((lit(10_i64) / col("x")).gt(lit(0_i64))),
None,
)
.gt(lit(0_i64))
.or(col("ord").eq(lit(2_i64))),
),
(
"non-boolean filter",
sum_window(col("x"), Some(col("x")), None)
.gt(lit(0_i64))
.or(col("ord").eq(lit(2_i64))),
),
(
"untyped null filter",
sum_window(col("x"), Some(lit(ScalarValue::Null)), None)
.gt(lit(0_i64))
.or(col("ord").eq(lit(2_i64))),
),
(
"untyped null filter on FIRST_VALUE",
agg_window(
first_value_udaf(),
col("x"),
Some(lit(ScalarValue::Null)),
None,
)
.gt(lit(0_i64))
.or(col("ord").eq(lit(2_i64))),
),
(
"fallible order_by",
sum_window(col("x"), Some(a_mask()), Some(lit(10_i64) / col("x")))
.gt(lit(0_i64))
.or(col("ord").eq(lit(2_i64))),
),
(
"volatile arg",
sum_window(random(), Some(a_mask()), None)
.gt(lit(0.0_f64))
.or(col("ord").eq(lit(2_i64))),
),
(
"volatile filter",
sum_window(col("x"), Some(random().gt(lit(0.0_f64))), None)
.gt(lit(0_i64))
.or(col("ord").eq(lit(2_i64))),
),
(
"volatile order_by",
sum_window(col("x"), Some(a_mask()), Some(random()))
.gt(lit(0_i64))
.or(col("ord").eq(lit(2_i64))),
),
("uncoerced AVG(Int64)", uncoerced_avg_b),
("unproven aggregate UDAF", array_agg_b),
] {
assert_eq!(
compile_hybrid_b_guard(unsafe_b)?,
LogicalHybridGuardExpr::Unknown,
"{label} must disable speculative Hybrid guard short-circuiting"
);
}
let null_col_filter_b =
agg_window(first_value_udaf(), col("x"), Some(col("null_flag")), None)
.gt(lit(0_i64))
.or(col("ord").eq(lit(2_i64)));
assert_eq!(
compile_hybrid_b_guard_with_schema(
vec![Field::new("null_flag", DataType::Null, true)],
safe_a_deferred(),
null_col_filter_b,
)?,
LogicalHybridGuardExpr::Unknown,
"DataType::Null column filter must disable Hybrid guard"
);
let bool_null_filter_b =
sum_window(col("x"), Some(lit(ScalarValue::Boolean(None))), None)
.gt(lit(0_i64))
.or(col("ord").eq(lit(2_i64)));
assert_eq!(compile_hybrid_b_guard(bool_null_filter_b)?, expected_active);
let int_list =
DataType::List(Arc::new(Field::new("item", DataType::Int64, true)));
let nested_list =
DataType::List(Arc::new(Field::new("item", int_list.clone(), true)));
let struct_with_list =
DataType::Struct(vec![Arc::new(Field::new("a", int_list, true))].into());
let dictionary =
DataType::Dictionary(Box::new(DataType::Int8), Box::new(DataType::Utf8));
let run_end = DataType::RunEndEncoded(
Arc::new(Field::new("run_ends", DataType::Int32, false)),
Arc::new(Field::new("values", DataType::Int64, true)),
);
for (label, key_type, expect_active) in [
("scalar Int64", DataType::Int64, true),
("nested List<List<Int64>>", nested_list, false),
("Struct<List<Int64>>", struct_with_list, false),
("Dictionary", dictionary, false),
("RunEndEncoded", run_end, false),
] {
for (fn_name, udaf) in [
("FIRST_VALUE", first_value_udaf()),
("LAST_VALUE", last_value_udaf()),
] {
let b_deferred =
agg_window(udaf, col("x"), Some(a_mask()), Some(col("k")))
.gt(lit(0_i64))
.or(col("ord").eq(lit(2_i64)));
let actual = compile_hybrid_b_guard_with_schema(
vec![Field::new("k", key_type.clone(), true)],
safe_a_deferred(),
b_deferred,
)?;
let expected = if expect_active {
expected_active.clone()
} else {
LogicalHybridGuardExpr::Unknown
};
assert_eq!(actual, expected, "{fn_name} ORDER BY {label}");
}
}
Ok(())
}
#[test]
fn deferred_aggregate_infallibility_rejects_sum_float32_and_union_order_key()
-> Result<()> {
let union_type = DataType::Union(
UnionFields::from_iter([(
0,
Arc::new(Field::new("value", DataType::Int64, true)),
)]),
UnionMode::Dense,
);
let schema = DFSchema::try_from(Schema::new(vec![
Field::new("x", DataType::Int64, false),
Field::new("f32", DataType::Float32, false),
Field::new("f64", DataType::Float64, false),
Field::new("u", union_type, true),
]))?;
let sum_f64 = WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(sum_udaf()),
vec![col("f64")],
);
let sum_f32 = WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(sum_udaf()),
vec![col("f32")],
);
assert!(deferred_aggregate_is_infallible(
sum_udaf().as_ref(),
&sum_f64,
&DataType::Float64,
&schema,
));
assert!(!deferred_aggregate_is_infallible(
sum_udaf().as_ref(),
&sum_f64,
&DataType::Float32,
&schema,
));
assert!(!deferred_aggregate_is_infallible(
sum_udaf().as_ref(),
&sum_f32,
&DataType::Float64,
&schema,
));
for udaf in [first_value_udaf(), last_value_udaf()] {
let mut window = WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(Arc::clone(&udaf)),
vec![col("x")],
);
window.params.order_by = vec![col("u").sort(true, true)];
assert!(!deferred_aggregate_is_infallible(
udaf.as_ref(),
&window,
&DataType::Int64,
&schema,
));
}
Ok(())
}
#[test]
fn deferred_aggregate_infallibility_rejects_distinct_aggregates() -> Result<()> {
let int_list =
DataType::List(Arc::new(Field::new("item", DataType::Int64, true)));
let schema = DFSchema::try_from(Schema::new(vec![
Field::new("x", DataType::Int64, false),
Field::new("f64", DataType::Float64, false),
Field::new("xs", int_list, true),
]))?;
for (label, udaf, arg, result_type) in [
("SUM(Int64)", sum_udaf(), col("x"), DataType::Int64),
("SUM(Float64)", sum_udaf(), col("f64"), DataType::Float64),
("AVG(Float64)", avg_udaf(), col("f64"), DataType::Float64),
("COUNT(Int64)", count_udaf(), col("x"), DataType::Int64),
(
"COUNT(List<Int64>)",
count_udaf(),
col("xs"),
DataType::Int64,
),
("MIN(Int64)", min_udaf(), col("x"), DataType::Int64),
("MAX(Int64)", max_udaf(), col("x"), DataType::Int64),
] {
let mut window = WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(Arc::clone(&udaf)),
vec![arg],
);
assert!(
deferred_aggregate_is_infallible(
udaf.as_ref(),
&window,
&result_type,
&schema,
),
"non-distinct {label} should remain infallible"
);
window.params.distinct = true;
assert!(
!deferred_aggregate_is_infallible(
udaf.as_ref(),
&window,
&result_type,
&schema,
),
"DISTINCT {label} must not be treated as infallible"
);
}
let distinct_window = |udaf, arg: Expr| {
let mut window = WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(udaf),
vec![arg],
);
window.params.distinct = true;
Expr::WindowFunction(Box::new(window))
};
for (label, distinct_b) in [
(
"SUM(DISTINCT Int64)",
distinct_window(sum_udaf(), col("x"))
.gt(lit(0_i64))
.or(col("ord").eq(lit(2_i64))),
),
(
"AVG(DISTINCT Float64)",
distinct_window(
avg_udaf(),
Expr::Cast(Cast::new(Box::new(col("x")), DataType::Float64)),
)
.gt(lit(0.0_f64))
.or(col("ord").eq(lit(2_i64))),
),
(
"COUNT(DISTINCT Int64)",
distinct_window(count_udaf(), col("x"))
.gt(lit(0_i64))
.or(col("ord").eq(lit(2_i64))),
),
] {
assert_eq!(
compile_hybrid_b_guard(distinct_b)?,
LogicalHybridGuardExpr::Unknown,
"{label} must disable speculative Hybrid guard short-circuiting"
);
}
Ok(())
}
#[test]
fn hybrid_symbol_preserves_guard_with_accumulator_state() -> Result<()> {
let safe_b = Expr::WindowFunction(Box::new(WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(sum_udaf()),
vec![col("x")],
)))
.gt(lit(0_i64))
.or(col("ord").eq(lit(2_i64)));
let routed = compile_hybrid_b_routed_with_schema(
vec![],
safe_a_deferred(),
safe_b,
MatchCompilerOptions::new(true),
)?;
assert_eq!(
routed.aggregates()[0].backend(),
ManagedAggregateBackend::Accumulator
);
let symbol_b = &routed.symbols()[1];
assert_eq!(
symbol_b.evaluator().hybrid_guard(),
Some(&LogicalHybridGuardExpr::Or(
Box::new(LogicalHybridGuardExpr::Unknown),
Box::new(LogicalHybridGuardExpr::Local(col("ord").eq(lit(2_i64)))),
))
);
Ok(())
}
#[test]
fn deferred_infallibility_and_hybrid_guard_reject_null_min_max_and_run_end()
-> Result<()> {
let run_end = DataType::RunEndEncoded(
Arc::new(Field::new("run_ends", DataType::Int32, false)),
Arc::new(Field::new("values", DataType::Int64, true)),
);
let list_run_end =
DataType::List(Arc::new(Field::new("item", run_end.clone(), true)));
let list_i64 =
DataType::List(Arc::new(Field::new("item", DataType::Int64, true)));
let schema = DFSchema::try_from(Schema::new(vec![
Field::new("x", DataType::Int64, false),
Field::new("null_col", DataType::Null, true),
Field::new("ree_col", run_end.clone(), true),
Field::new("list_ree_col", list_run_end.clone(), true),
Field::new("list_i64_col", list_i64.clone(), true),
]))?;
for udaf in [min_udaf(), max_udaf()] {
let window = WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(Arc::clone(&udaf)),
vec![col("null_col")],
);
assert!(
!deferred_aggregate_is_infallible(
udaf.as_ref(),
&window,
&DataType::Null,
&schema,
),
"{} on DataType::Null must not be infallible",
udaf.name()
);
}
for udaf in [first_value_udaf(), last_value_udaf()] {
for (label, col_name, result_type, expected) in [
("Int64", "x", DataType::Int64, true),
("List<Int64>", "list_i64_col", list_i64.clone(), true),
("RunEndEncoded", "ree_col", run_end.clone(), false),
(
"List<RunEndEncoded>",
"list_ree_col",
list_run_end.clone(),
false,
),
] {
let window = WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(Arc::clone(&udaf)),
vec![col(col_name)],
);
assert_eq!(
deferred_aggregate_is_infallible(
udaf.as_ref(),
&window,
&result_type,
&schema,
),
expected,
"{}({label})",
udaf.name()
);
}
}
let expected_active = LogicalHybridGuardExpr::Or(
Box::new(LogicalHybridGuardExpr::Unknown),
Box::new(LogicalHybridGuardExpr::Local(col("ord").eq(lit(2_i64)))),
);
let a_mask = || col(classifier_bits_col_name("A"));
let agg_window = |udaf, arg: Expr| {
let mut window = WindowFunction::new(
WindowFunctionDefinition::AggregateUDF(udaf),
vec![arg],
);
window.params.filter = Some(Box::new(a_mask()));
Expr::WindowFunction(Box::new(window))
};
for udaf in [first_value_udaf(), last_value_udaf()] {
let safe_b = agg_window(Arc::clone(&udaf), col("x"))
.is_not_null()
.or(col("ord").eq(lit(2_i64)));
assert_eq!(compile_hybrid_b_guard(safe_b)?, expected_active);
for (label, extra_type) in [
("RunEndEncoded", run_end.clone()),
("List<RunEndEncoded>", list_run_end.clone()),
] {
let unsafe_b = agg_window(Arc::clone(&udaf), col("ree"))
.is_not_null()
.or(col("ord").eq(lit(2_i64)));
assert_eq!(
compile_hybrid_b_guard_with_schema(
vec![Field::new("ree", extra_type, true)],
safe_a_deferred(),
unsafe_b,
)?,
LogicalHybridGuardExpr::Unknown,
"{}({label}) must disable Hybrid guard",
udaf.name()
);
}
}
let safe_b = agg_window(sum_udaf(), col("x"))
.gt(lit(0_i64))
.or(col("ord").eq(lit(2_i64)));
for (label, extra_type) in [
("RunEndEncoded", run_end),
("List<RunEndEncoded>", list_run_end),
] {
let b_with_ree_extra = agg_window(sum_udaf(), col("x"))
.gt(lit(0_i64))
.and(col("ree").is_not_null())
.or(col("ord").eq(lit(2_i64)));
assert_eq!(
compile_hybrid_b_guard_with_schema(
vec![Field::new("ree", extra_type.clone(), true)],
safe_a_deferred(),
b_with_ree_extra,
)?,
LogicalHybridGuardExpr::Unknown,
"{label} in B predicate_extras must disable Hybrid guard"
);
let a_with_ree_extra = safe_a_deferred().and(col("ree").is_not_null());
assert_eq!(
compile_hybrid_b_guard_with_schema(
vec![Field::new("ree", extra_type, true)],
a_with_ree_extra,
safe_b.clone(),
)?,
LogicalHybridGuardExpr::Or(
Box::new(LogicalHybridGuardExpr::Unknown),
Box::new(LogicalHybridGuardExpr::Local(col("ord").eq(lit(2_i64)))),
),
"{label} in A predicate_extras must preserve B Hybrid guard"
);
}
Ok(())
}
}
#[cfg(test)]
mod predicate_compilation_tests {
use std::sync::Arc;
use crate::planning::logical::{LogicalManagedAggregate, LogicalSymbolId};
use crate::planning::predicate::{
VmCompileContext, VmCompileError, VmManagedPredicateColumn,
VmPredicateInputColumn, VmPredicateInputRole, VmScalarType, VmType,
compile_direct_predicate,
};
use datafusion::common::ScalarValue;
use datafusion::functions::math;
use datafusion::functions_aggregate::sum::sum;
use datafusion::logical_expr::expr::{AggregateFunction, WindowFunction};
use datafusion::logical_expr::{Expr, WindowFunctionDefinition, col, lit};
use datafusion_expr::expr::ScalarFunction;
fn support_context(
managed_columns: Vec<VmManagedPredicateColumn>,
input_columns: Vec<VmPredicateInputColumn>,
) -> VmCompileContext {
VmCompileContext::try_new(managed_columns, input_columns, Default::default())
.unwrap()
}
fn managed_numeric(expr: Expr) -> LogicalManagedAggregate {
let Expr::AggregateFunction(func) = expr else {
panic!("expected aggregate function");
};
LogicalManagedAggregate::for_test(0, func, Some(LogicalSymbolId::for_test(0)))
}
fn managed_first(column_name: &str) -> LogicalManagedAggregate {
let func = AggregateFunction::new_udf(
crate::functions::udaf::mr_first_udaf(),
vec![col(column_name)],
false,
None,
vec![],
None,
);
LogicalManagedAggregate::for_test(0, func, Some(LogicalSymbolId::for_test(0)))
}
fn call1(udf: Arc<datafusion_expr::ScalarUDF>, arg: Expr) -> Expr {
Expr::ScalarFunction(ScalarFunction::new_udf(udf, vec![arg]))
}
fn direct_prev(column_name: &str, classifier_name: &str) -> Expr {
let args = vec![
col(column_name),
lit(ScalarValue::UInt64(Some(1))),
lit(ScalarValue::Null),
crate::planning::logical::is_matched_expr(),
col(classifier_name),
];
Expr::WindowFunction(Box::new(WindowFunction {
fun: WindowFunctionDefinition::AggregateUDF(
crate::functions::udaf::mr_prev_udaf(),
),
params: crate::planning::bound_expr_lowering::canonical_define_navigation_window_params(
&[],
args,
),
}))
}
fn managed_column(
aggregate: &LogicalManagedAggregate,
scalar_type: Option<VmScalarType>,
) -> VmManagedPredicateColumn {
VmManagedPredicateColumn::new(
aggregate.id().index(),
aggregate.column_name(),
scalar_type,
)
}
#[test]
fn missing_managed_placeholder_reports_unsupported_source_domain() {
let managed = [managed_numeric(sum(col("x")))];
let input_columns = [VmPredicateInputColumn::new(
"x".to_string(),
Some(VmType::nullable(VmScalarType::Int64)),
VmPredicateInputRole::RowValue,
)];
let context = support_context(
vec![managed_column(&managed[0], None)],
input_columns.to_vec(),
);
let error =
compile_direct_predicate(&col("__mr_managed_agg_0").gt(lit(0_i64)), &context)
.unwrap_err();
assert_eq!(error, VmCompileError::UnsupportedSourceDomain);
}
#[test]
fn compile_predicate_accepts_q16_decimal_subtraction() {
let managed = [managed_first("l_quantity")];
let decimal_scalar = VmScalarType::Decimal128 {
precision: 15,
scale: 2,
};
let input_columns = [VmPredicateInputColumn::new(
"l_quantity".to_string(),
Some(VmType::nullable(decimal_scalar)),
VmPredicateInputRole::RowValue,
)];
let context = support_context(
vec![managed_column(&managed[0], Some(decimal_scalar))],
input_columns.to_vec(),
);
let expr = call1(math::abs(), col("l_quantity") - col("__mr_managed_agg_0"))
.lt_eq(lit(ScalarValue::Decimal128(Some(200), 16, 2)));
assert!(compile_direct_predicate(&expr, &context).is_ok());
let subtraction = (col("l_quantity") - col("__mr_managed_agg_0"))
.lt_eq(lit(ScalarValue::Decimal128(Some(200), 16, 2)));
assert!(compile_direct_predicate(&subtraction, &context).is_ok());
}
#[test]
fn managed_values_compile_while_raw_navigation_calls_fall_back() {
for (scalar, threshold) in [
(
VmScalarType::Decimal256 {
precision: 50,
scale: 2,
},
ScalarValue::Decimal256(
Some(datafusion::arrow::datatypes::i256::from_i128(0)),
50,
2,
),
),
(
VmScalarType::FixedSizeBinary(4),
ScalarValue::FixedSizeBinary(4, Some(vec![1, 2, 3, 4])),
),
(VmScalarType::Utf8, ScalarValue::Utf8(Some("anchor".into()))),
(
VmScalarType::LargeUtf8,
ScalarValue::LargeUtf8(Some("anchor".into())),
),
(
VmScalarType::Utf8View,
ScalarValue::Utf8View(Some("anchor".into())),
),
] {
let input_columns = vec![
VmPredicateInputColumn::new(
"x".to_string(),
Some(VmType::nullable(scalar)),
VmPredicateInputRole::RowValue,
),
VmPredicateInputColumn::new(
"__mr_classifier_a".to_string(),
Some(VmType::nullable(VmScalarType::Bool)),
VmPredicateInputRole::Classifier,
),
];
let context = support_context(
vec![VmManagedPredicateColumn::new(
0,
"managed".to_string(),
Some(scalar),
)],
input_columns,
);
let threshold = lit(threshold);
let result =
compile_direct_predicate(&col("managed").eq(threshold.clone()), &context);
if matches!(
scalar,
VmScalarType::Decimal256 { .. } | VmScalarType::FixedSizeBinary(_)
) {
assert!(result.is_err());
} else {
assert!(result.is_ok());
}
let direct = direct_prev("x", "__mr_classifier_a").eq(threshold);
assert!(compile_direct_predicate(&direct, &context).is_err());
}
}
}