use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use crate::nfa::SymbolStatus;
use crate::planning::logical::{
InternalSlotOwner, LogicalMatchProgram, LogicalSymbolPredicate,
};
use datafusion::arrow::datatypes::{DataType, Schema, SchemaRef};
use datafusion::logical_expr::Operator;
use datafusion_common::pruning::PrunableStatistics;
use datafusion_common::stats::Precision;
use datafusion_common::{DFSchema, ScalarValue, Statistics};
use datafusion_physical_expr::expressions::{BinaryExpr, Literal};
use datafusion_physical_expr_common::physical_expr::is_volatile;
use datafusion_physical_plan::operator_statistics::StatisticsRegistry;
use datafusion_physical_plan::projection::ProjectionExec;
use datafusion_physical_plan::statistics::{StatisticsArgs, StatisticsContext};
use datafusion_physical_plan::{ExecutionPlan, PhysicalExpr};
use datafusion_pruning::PruningPredicateBuilder;
pub(in crate::execution) fn exact_static_symbol_absence(
program: &LogicalMatchProgram,
logical_schema: &DFSchema,
input: &Arc<dyn ExecutionPlan>,
registry: Option<&StatisticsRegistry>,
) -> HashMap<String, SymbolStatus> {
if !program.can_skip_candidate_evaluation(logical_schema) {
return HashMap::new();
}
let Some(projection) = input.downcast_ref::<ProjectionExec>() else {
return HashMap::new();
};
let statistics_input = projection.input();
let statistics_schema = statistics_input.schema();
if !has_unique_field_names(statistics_schema.as_ref()) {
return HashMap::new();
}
let context = registry
.cloned()
.map(StatisticsContext::new_with_registry)
.unwrap_or_default();
let Ok(statistics) =
context.compute(statistics_input.as_ref(), &StatisticsArgs::new())
else {
return HashMap::new();
};
let pruning_statistics = pruning_statistics(statistics, &statistics_schema);
let mut absent = HashMap::new();
for symbol in program.symbols() {
if !matches!(symbol.predicate(), LogicalSymbolPredicate::Static { .. }) {
continue;
}
let Some(alias) =
program.internal_slot_name(InternalSlotOwner::SymbolResult(symbol.id()))
else {
continue;
};
let Some(predicate) = unique_projection_expr(projection, &alias) else {
continue;
};
if predicate_is_proven_absent(predicate, &statistics_schema, &pruning_statistics)
{
absent.insert(symbol.name().to_owned(), SymbolStatus::False);
}
}
absent
}
fn pruning_statistics(
mut statistics: Arc<Statistics>,
schema: &SchemaRef,
) -> PrunableStatistics {
for (index, field) in schema.fields().iter().enumerate() {
if has_float_leaf(field.data_type())
&& let Some(column) = Arc::make_mut(&mut statistics)
.column_statistics
.get_mut(index)
{
column.min_value = Precision::Absent;
column.max_value = Precision::Absent;
}
}
PrunableStatistics::new(vec![statistics], Arc::clone(schema))
}
fn has_float_leaf(data_type: &DataType) -> bool {
match data_type {
DataType::Float16 | DataType::Float32 | DataType::Float64 => true,
DataType::List(field)
| DataType::LargeList(field)
| DataType::FixedSizeList(field, _)
| DataType::ListView(field)
| DataType::LargeListView(field)
| DataType::Map(field, _) => has_float_leaf(field.data_type()),
DataType::Struct(fields) => {
fields.iter().any(|field| has_float_leaf(field.data_type()))
}
DataType::Dictionary(key, value) => has_float_leaf(key) || has_float_leaf(value),
DataType::Union(fields, _) => fields
.iter()
.any(|(_, field)| has_float_leaf(field.data_type())),
DataType::RunEndEncoded(run_ends, values) => {
has_float_leaf(run_ends.data_type()) || has_float_leaf(values.data_type())
}
_ => false,
}
}
fn unique_projection_expr(
projection: &ProjectionExec,
alias: &str,
) -> Option<Arc<dyn PhysicalExpr>> {
let mut matching = projection.expr().iter().filter(|expr| expr.alias == alias);
let expression = Arc::clone(&matching.next()?.expr);
matching.next().is_none().then_some(expression)
}
fn has_unique_field_names(schema: &Schema) -> bool {
let mut names = HashSet::with_capacity(schema.fields().len());
schema
.fields()
.iter()
.all(|field| names.insert(field.name().as_str()))
}
fn predicate_is_proven_absent(
predicate: Arc<dyn PhysicalExpr>,
schema: &SchemaRef,
statistics: &PrunableStatistics,
) -> bool {
if is_volatile(&predicate)
|| predicate.data_type(schema.as_ref()).ok() != Some(DataType::Boolean)
{
return false;
}
let predicate = if let Some(binary) = predicate.downcast_ref::<BinaryExpr>()
&& *binary.op() == Operator::IsNotDistinctFrom
{
let is_true = |expr: &Arc<dyn PhysicalExpr>| {
expr.downcast_ref::<Literal>().is_some_and(|literal| {
literal.value() == &ScalarValue::Boolean(Some(true))
})
};
if is_true(binary.right()) {
Arc::clone(binary.left())
} else if is_true(binary.left()) {
Arc::clone(binary.right())
} else {
predicate
}
} else {
predicate
};
let Ok(pruning_predicate) = PruningPredicateBuilder::new()
.with_file_schema(Arc::clone(schema))
.try_build(predicate)
else {
return false;
};
pruning_predicate
.prune(statistics)
.is_ok_and(|result| result.as_slice() == [false])
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::{
AfterMatchSkip, MatchRecognizeOutputSpec, Pattern, RowsPerMatch, Symbol,
};
use crate::planning::SymbolRelationships;
use crate::planning::logical::{
LogicalMatchOutput, LogicalMatchProgramInput, LogicalSymbolInput, MatchRecognize,
};
use datafusion::arrow::datatypes::Field;
use datafusion::logical_expr::{LogicalPlanBuilder, col, lit};
use datafusion_common::stats::ColumnStatistics;
use datafusion_physical_expr::expressions::Column;
use datafusion_physical_plan::operator_statistics::{
ClosureStatisticsProvider, StatisticsResult,
};
use datafusion_physical_plan::test::exec::StatisticsExec;
use std::sync::atomic::{AtomicUsize, Ordering};
fn two_symbol_node() -> datafusion_common::Result<MatchRecognize> {
MatchRecognize::try_new(
LogicalPlanBuilder::empty(false)
.project(vec![lit(1_i64).alias("x")])?
.project(vec![
col("x"),
col("x")
.gt(lit(100_i64))
.alias(crate::core::symbol_col_name("A")),
col("x")
.gt(lit(200_i64))
.alias(crate::core::symbol_col_name("B")),
])?
.build()?,
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::static_("A", col("x").gt(lit(100_i64))),
LogicalSymbolInput::static_("B", col("x").gt(lit(200_i64))),
],
match_aware: None,
output: LogicalMatchOutput::rows(
RowsPerMatch::OneRow,
MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
),
symbol_relationships: SymbolRelationships::default(),
},
)
}
fn projected_statistics_source(
node: &MatchRecognize,
schema: SchemaRef,
statistics: Statistics,
) -> datafusion_common::Result<Arc<dyn ExecutionPlan>> {
let source = Arc::new(StatisticsExec::new(statistics, schema.as_ref().clone()));
let expressions = node
.program()
.symbols()
.iter()
.zip([100, 200])
.map(|(symbol, bound)| {
(
greater_than(bound),
node.program()
.internal_slot_name(InternalSlotOwner::SymbolResult(symbol.id()))
.unwrap(),
)
})
.collect::<Vec<_>>();
Ok(Arc::new(ProjectionExec::try_new(expressions, source)?))
}
#[test]
fn registry_proofs_share_one_walk_and_provider_errors_remain_unknown()
-> datafusion_common::Result<()> {
let node = two_symbol_node()?;
let schema = int64_schema();
let input = projected_statistics_source(
&node,
Arc::clone(&schema),
Statistics::new_unknown(schema.as_ref()),
)?;
assert!(
exact_static_symbol_absence(
node.program(),
node.input().schema().as_ref(),
&input,
None,
)
.is_empty()
);
for fail in [false, true] {
let calls = Arc::new(AtomicUsize::new(0));
let provider_calls = Arc::clone(&calls);
let registry = StatisticsRegistry::with_providers(vec![Arc::new(
ClosureStatisticsProvider::new(move |_, _| {
provider_calls.fetch_add(1, Ordering::Relaxed);
if fail {
return datafusion_common::exec_err!("statistics unavailable");
}
let exact = |value| Precision::Exact(ScalarValue::Int64(Some(value)));
Ok(StatisticsResult::Computed(
statistics(exact(0), exact(10), Precision::Exact(0)).into(),
))
}),
)]);
let absent = exact_static_symbol_absence(
node.program(),
node.input().schema().as_ref(),
&input,
Some(®istry),
);
if fail {
assert!(absent.is_empty());
} else {
assert_eq!(
absent,
HashMap::from([
("A".to_string(), SymbolStatus::False),
("B".to_string(), SymbolStatus::False)
])
);
}
assert_eq!(calls.load(Ordering::Relaxed), 1);
}
Ok(())
}
fn int64_schema() -> SchemaRef {
Arc::new(Schema::new(vec![Field::new("x", DataType::Int64, true)]))
}
fn greater_than(value: i64) -> Arc<dyn PhysicalExpr> {
Arc::new(BinaryExpr::new(
Arc::new(Column::new("x", 0)),
Operator::Gt,
Arc::new(Literal::new(ScalarValue::Int64(Some(value)))),
))
}
fn statistics(
min_value: Precision<ScalarValue>,
max_value: Precision<ScalarValue>,
null_count: Precision<usize>,
) -> Statistics {
Statistics {
num_rows: Precision::Exact(10),
total_byte_size: Precision::Absent,
column_statistics: vec![
ColumnStatistics::new_unknown()
.with_min_value(min_value)
.with_max_value(max_value)
.with_null_count(null_count),
],
}
}
#[test]
fn only_exact_statistics_can_prove_absence() {
let schema = int64_schema();
let exact = |value| Precision::Exact(ScalarValue::Int64(Some(value)));
let inexact = |value| Precision::Inexact(ScalarValue::Int64(Some(value)));
let cases = [
(
"exact excluding range",
statistics(exact(0), exact(10), Precision::Exact(0)),
true,
),
(
"exact overlapping range",
statistics(exact(0), exact(200), Precision::Exact(0)),
false,
),
(
"inexact excluding range",
statistics(inexact(0), inexact(10), Precision::Inexact(0)),
false,
),
(
"absent statistics",
Statistics::new_unknown(schema.as_ref()),
false,
),
(
"exact all-null column",
statistics(Precision::Absent, Precision::Absent, Precision::Exact(10)),
true,
),
];
for (name, statistics, expected) in cases {
let statistics =
PrunableStatistics::new(vec![Arc::new(statistics)], Arc::clone(&schema));
assert_eq!(
predicate_is_proven_absent(greater_than(100), &schema, &statistics),
expected,
"{name}"
);
}
}
#[test]
fn float_bounds_cannot_prove_absence_but_all_null_counts_can() {
for data_type in [DataType::Float32, DataType::Float64] {
let scalar = |value| {
ScalarValue::Float64(Some(value))
.cast_to(&data_type)
.unwrap()
};
let schema =
Arc::new(Schema::new(vec![Field::new("x", data_type.clone(), true)]));
let predicate: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
Arc::new(Column::new("x", 0)),
Operator::Gt,
Arc::new(Literal::new(scalar(100.0))),
));
for (null_count, expected) in [(0, false), (3, true)] {
let mut source = statistics(
Precision::Exact(scalar(1.0)),
Precision::Exact(scalar(2.0)),
Precision::Exact(null_count),
);
source.num_rows = Precision::Exact(3);
let statistics = pruning_statistics(Arc::new(source), &schema);
assert_eq!(
predicate_is_proven_absent(
Arc::clone(&predicate),
&schema,
&statistics
),
expected,
"{data_type:?}, null_count={null_count}"
);
}
}
}
#[test]
fn nullable_define_wrappers_preserve_comparison_and_compound_proofs() {
let schema = int64_schema();
let exact = |value| Precision::Exact(ScalarValue::Int64(Some(value)));
let statistics = pruning_statistics(
Arc::new(statistics(exact(0), exact(10), Precision::Exact(2))),
&schema,
);
for compound in [false, true] {
for (bound, expected) in [(100, true), (5, false)] {
let predicate = greater_than(bound);
let predicate: Arc<dyn PhysicalExpr> = if compound {
Arc::new(BinaryExpr::new(predicate, Operator::And, greater_than(0)))
} else {
predicate
};
for symmetric in [false, true] {
let literal: Arc<dyn PhysicalExpr> =
Arc::new(Literal::new(ScalarValue::Boolean(Some(true))));
let (left, right) = if symmetric {
(literal, Arc::clone(&predicate))
} else {
(Arc::clone(&predicate), literal)
};
let wrapped = Arc::new(BinaryExpr::new(
left,
Operator::IsNotDistinctFrom,
right,
));
assert_eq!(
predicate_is_proven_absent(wrapped, &schema, &statistics),
expected,
"compound={compound}, symmetric={symmetric}, bound={bound}"
);
}
}
}
}
#[test]
fn duplicate_source_names_keep_conflicting_ordinal_statistics_unknown()
-> datafusion_common::Result<()> {
let node = two_symbol_node()?;
let exact = |value| Precision::Exact(ScalarValue::Int64(Some(value)));
for duplicate in [false, true] {
let schema = Arc::new(Schema::new(vec![
Field::new("x", DataType::Int64, true),
Field::new(if duplicate { "x" } else { "y" }, DataType::Int64, true),
]));
let mut source = statistics(exact(0), exact(10), Precision::Exact(0));
source.column_statistics.push(
ColumnStatistics::new_unknown()
.with_min_value(exact(500))
.with_max_value(exact(600))
.with_null_count(Precision::Exact(0)),
);
let input = projected_statistics_source(&node, schema, source)?;
let absent = exact_static_symbol_absence(
node.program(),
node.input().schema().as_ref(),
&input,
None,
);
if duplicate {
assert!(
absent.is_empty(),
"ambiguous names must fail open despite exact excluding statistics"
);
} else {
assert_eq!(
absent,
HashMap::from([
("A".to_string(), SymbolStatus::False),
("B".to_string(), SymbolStatus::False)
])
);
}
}
Ok(())
}
#[test]
fn match_aware_absence_pruning_gates_on_can_skip_candidate_evaluation()
-> datafusion_common::Result<()> {
use crate::core::MatchMetadataColumn;
use datafusion::arrow::array::BooleanArray;
use datafusion::logical_expr::{
ColumnarValue, Volatility, binary_expr, create_udf,
};
let logical_input = LogicalPlanBuilder::empty(false)
.project(vec![lit(1_i64).alias("x"), lit(0_i64).alias("denom")])?
.project(vec![
col("x"),
col("denom"),
col("x")
.gt(lit(100_i64))
.alias(crate::core::symbol_col_name("B")),
])?
.build()?;
let volatile_udf = create_udf(
"volatile_absence_probe",
vec![DataType::Int64],
DataType::Boolean,
Volatility::Volatile,
Arc::new(|args: &[ColumnarValue]| {
let rows = match &args[0] {
ColumnarValue::Array(array) => array.len(),
ColumnarValue::Scalar(_) => 1,
};
Ok(ColumnarValue::Array(Arc::new(BooleanArray::from(vec![
true;
rows
]))))
}),
);
let schema = Arc::new(Schema::new(vec![
Field::new("x", DataType::Int64, false),
Field::new("denom", DataType::Int64, false),
]));
let cases = [
(
"fallible incremental DEFINE",
LogicalSymbolInput::incremental(
"A",
binary_expr(lit(1_i64), Operator::Divide, col("denom"))
.gt(lit(0_i64)),
),
false,
),
(
"volatile incremental DEFINE",
LogicalSymbolInput::incremental("A", volatile_udf.call(vec![col("x")])),
false,
),
(
"deferred DEFINE",
LogicalSymbolInput::deferred(
"A",
col(MatchMetadataColumn::MatchNumber.as_ref()).gt(lit(0_i64)),
),
false,
),
(
"safe incremental DEFINE",
LogicalSymbolInput::incremental("A", col("x").gt(lit(0_i64))),
true,
),
];
for (label, symbol_a, expected_can_skip) in cases {
let node = MatchRecognize::try_new(
logical_input.clone(),
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![
symbol_a,
LogicalSymbolInput::static_("B", col("x").gt(lit(100_i64))),
],
match_aware: None,
output: LogicalMatchOutput::rows(
RowsPerMatch::OneRow,
MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
),
symbol_relationships: SymbolRelationships::default(),
},
)?;
assert!(node.program().requires_match_aware_defines(), "{label}");
assert_eq!(
node.program()
.can_skip_candidate_evaluation(node.input().schema().as_ref()),
expected_can_skip,
"{label}"
);
let source = Arc::new(StatisticsExec::new(
Statistics::new_unknown(schema.as_ref()),
schema.as_ref().clone(),
));
let b_alias = node
.program()
.internal_slot_name(InternalSlotOwner::SymbolResult(
node.program().symbols()[1].id(),
))
.unwrap();
let input: Arc<dyn ExecutionPlan> = Arc::new(ProjectionExec::try_new(
vec![(greater_than(100), b_alias)],
source,
)?);
let calls = Arc::new(AtomicUsize::new(0));
let provider_calls = Arc::clone(&calls);
let registry = StatisticsRegistry::with_providers(vec![Arc::new(
ClosureStatisticsProvider::new(move |_, _| {
provider_calls.fetch_add(1, Ordering::Relaxed);
let exact = |value| Precision::Exact(ScalarValue::Int64(Some(value)));
Ok(StatisticsResult::Computed(
Statistics {
num_rows: Precision::Exact(2),
total_byte_size: Precision::Absent,
column_statistics: vec![
ColumnStatistics::new_unknown()
.with_min_value(exact(0))
.with_max_value(exact(10))
.with_null_count(Precision::Exact(0)),
ColumnStatistics::new_unknown()
.with_min_value(exact(0))
.with_max_value(exact(0))
.with_null_count(Precision::Exact(0)),
],
}
.into(),
))
}),
)]);
let absent = exact_static_symbol_absence(
node.program(),
node.input().schema().as_ref(),
&input,
Some(®istry),
);
if expected_can_skip {
assert_eq!(
absent,
HashMap::from([("B".to_string(), SymbolStatus::False)]),
"{label}"
);
assert_eq!(calls.load(Ordering::Relaxed), 1, "{label}");
} else {
assert!(absent.is_empty(), "{label}");
assert_eq!(calls.load(Ordering::Relaxed), 0, "{label}");
}
}
Ok(())
}
}