use crate::execution::matching::{
ExecutableOutputPlan, ResolvedBoolColumn, ResolvedInputColumn, SymbolColumn,
};
use std::sync::Arc;
use crate::core::vm::{RegisterLayout, is_temporal_word_type};
use crate::core::{
AggregateId, NormalizedPattern, StaticPredicateKind, SymbolEvalMode, SymbolId,
};
#[cfg(test)]
use crate::core::{MatchRecognizeOutputSpec, RowsPerMatch};
use crate::planning::predicate::{DirectPredicatePlan, VmSourceRef};
use crate::planning::{
AccumulatorInputMode, ManagedAggregateBackend, RoutedPredicate, SymbolRelationships,
};
use datafusion::arrow::datatypes::{DataType, Schema, SchemaRef};
use datafusion::common::{DataFusionError, Result, internal_err};
use datafusion::logical_expr::expr::AggregateFunction;
use datafusion::physical_expr::aggregate::AggregateFunctionExpr;
use datafusion::physical_expr_common::physical_expr::is_volatile;
use datafusion::physical_plan::PhysicalExpr;
use crate::execution::deferred::DeferredEvaluatorFactory;
use crate::execution::deferred::DeferredHistoryProjection;
use crate::execution::matching::ResolvedAfterMatchSkip;
use crate::nfa::CompiledAutomaton;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ScalarColumnBinding {
pub(crate) column: ResolvedInputColumn,
}
impl ScalarColumnBinding {
pub(crate) fn try_from_data_type(
column: ResolvedInputColumn,
data_type: &DataType,
) -> Option<Self> {
let supported = matches!(
data_type,
DataType::Boolean
| DataType::Float32
| DataType::Float64
| DataType::Decimal128(_, _)
| DataType::Decimal256(_, _)
| DataType::FixedSizeBinary(_)
| DataType::Utf8
| DataType::LargeUtf8
| DataType::Utf8View
) || data_type.is_integer()
|| is_temporal_word_type(data_type);
supported.then_some(Self { column })
}
}
#[derive(Debug, Clone, Default)]
pub(crate) struct ResolvedVmStaticInputs(
Vec<ResolvedBoolColumn>,
Vec<Option<ScalarColumnBinding>>,
);
impl ResolvedVmStaticInputs {
pub(crate) fn try_new_for_selected_predicates(
predicates: Vec<ResolvedBoolColumn>,
scalars: Vec<Option<ScalarColumnBinding>>,
required_predicates: usize,
required_scalars: usize,
) -> Result<Self> {
if predicates.len() != required_predicates {
return internal_err!(
"MATCH_RECOGNIZE VM static predicate bindings are not aligned"
);
}
if scalars.len() != required_scalars {
return internal_err!(
"MATCH_RECOGNIZE VM static scalar bindings are not aligned"
);
}
Ok(Self(predicates, scalars))
}
pub(crate) fn into_parts(
self,
) -> (Vec<ResolvedBoolColumn>, Vec<Option<ScalarColumnBinding>>) {
(self.0, self.1)
}
}
#[derive(Debug, Clone)]
pub(crate) struct ResolvedStaticExtraction {
pub(crate) symbol_id: SymbolId,
pub(crate) column: ResolvedBoolColumn,
pub(crate) kind: StaticPredicateKind,
pub(crate) expr_display: String,
}
#[derive(Clone)]
pub(crate) enum PhysicalHybridGuardExpr {
Local(Arc<dyn PhysicalExpr>),
Unknown,
And(Box<PhysicalHybridGuardExpr>, Box<PhysicalHybridGuardExpr>),
Or(Box<PhysicalHybridGuardExpr>, Box<PhysicalHybridGuardExpr>),
Not(Box<PhysicalHybridGuardExpr>),
}
impl std::fmt::Debug for PhysicalHybridGuardExpr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Local(_) => f.write_str("Local(<expr>)"),
Self::Unknown => f.write_str("Unknown"),
Self::And(left, right) => {
f.debug_tuple("And").field(left).field(right).finish()
}
Self::Or(left, right) => {
f.debug_tuple("Or").field(left).field(right).finish()
}
Self::Not(inner) => f.debug_tuple("Not").field(inner).finish(),
}
}
}
impl PhysicalHybridGuardExpr {
pub(crate) fn evaluate_local(
&self,
local: &mut impl FnMut(&Arc<dyn PhysicalExpr>) -> Result<Option<bool>>,
) -> Result<Option<bool>> {
match self {
Self::Local(expr) => local(expr),
Self::Unknown => Ok(None),
Self::Not(inner) => Ok(inner.evaluate_local(local)?.map(|value| !value)),
Self::And(left, right) | Self::Or(left, right) => {
let decisive = matches!(self, Self::Or(_, _));
let left = left.evaluate_local(local)?;
if left == Some(decisive) {
return Ok(left);
}
let right = right.evaluate_local(local)?;
Ok(if left.is_some() {
right
} else {
right.filter(|&value| value == decisive)
})
}
}
}
pub(crate) fn append_physical_expr_roots(
&self,
roots: &mut Vec<Arc<dyn PhysicalExpr>>,
) {
match self {
Self::Local(expr) => roots.push(Arc::clone(expr)),
Self::Unknown => {}
Self::And(left, right) | Self::Or(left, right) => {
left.append_physical_expr_roots(roots);
right.append_physical_expr_roots(roots);
}
Self::Not(inner) => inner.append_physical_expr_roots(roots),
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct UserSymbolProgram {
pub(super) id: SymbolId,
pub(super) mode: SymbolEvalMode,
pub(super) deferred_history: DeferredHistoryProjection,
pub(super) local_predicate: Option<Arc<dyn PhysicalExpr>>,
pub(super) hybrid_guard: Option<PhysicalHybridGuardExpr>,
pub(super) register_writers: Vec<crate::core::vm::RegisterWriter>,
pub(super) selected_predicate: Option<DirectPredicatePlan>,
}
impl UserSymbolProgram {
pub(crate) fn try_new(
id: SymbolId,
mode: SymbolEvalMode,
local_predicate: Option<Arc<dyn PhysicalExpr>>,
hybrid_guard: Option<PhysicalHybridGuardExpr>,
register_writers: Vec<crate::core::vm::RegisterWriter>,
selected_predicate: Option<DirectPredicatePlan>,
) -> Result<Self> {
if local_predicate.is_some() != mode.uses_incremental() {
return internal_err!(
"MATCH_RECOGNIZE {mode} symbol {id} has inconsistent local predicate ownership"
);
}
if hybrid_guard.is_some() != matches!(mode, SymbolEvalMode::Hybrid) {
return internal_err!(
"MATCH_RECOGNIZE {mode} symbol {id} has inconsistent Hybrid guard ownership"
);
}
if selected_predicate.is_some() && !mode.uses_incremental() {
return internal_err!(
"MATCH_RECOGNIZE {mode} symbol {id} cannot own a direct predicate"
);
}
Ok(Self {
id,
mode,
deferred_history: DeferredHistoryProjection {
all_labels: true,
exclusions: true,
..Default::default()
},
local_predicate,
hybrid_guard,
register_writers,
selected_predicate,
})
}
pub(crate) const fn id(&self) -> SymbolId {
self.id
}
pub(crate) fn with_deferred_history(
mut self,
history: DeferredHistoryProjection,
) -> Self {
self.deferred_history = history;
self
}
pub(crate) fn deferred_history(&self) -> &DeferredHistoryProjection {
&self.deferred_history
}
pub(crate) fn register_writers(&self) -> &[crate::core::vm::RegisterWriter] {
&self.register_writers
}
pub(crate) fn selected_predicate(&self) -> Option<&DirectPredicatePlan> {
self.selected_predicate.as_ref()
}
pub(crate) const fn mode(&self) -> SymbolEvalMode {
self.mode
}
pub(crate) fn local_predicate(&self) -> Option<&Arc<dyn PhysicalExpr>> {
self.local_predicate.as_ref()
}
pub(crate) fn hybrid_guard(&self) -> Option<&PhysicalHybridGuardExpr> {
self.hybrid_guard.as_ref()
}
}
#[derive(Clone, Debug)]
#[allow(
clippy::large_enum_variant,
reason = "the dense symbol table keeps user programs contiguous; only slot zero is Empty"
)]
pub(crate) enum SymbolProgram {
Empty,
User(UserSymbolProgram),
}
impl SymbolProgram {
pub(crate) fn local_predicate(&self) -> Option<&Arc<dyn PhysicalExpr>> {
match self {
Self::Empty => None,
Self::User(program) => program.local_predicate(),
}
}
pub(crate) fn hybrid_guard(&self) -> Option<&PhysicalHybridGuardExpr> {
match self {
Self::Empty => None,
Self::User(program) => program.hybrid_guard(),
}
}
pub(crate) fn register_writers(&self) -> &[crate::core::vm::RegisterWriter] {
match self {
Self::Empty => &[],
Self::User(program) => program.register_writers(),
}
}
pub(crate) fn selected_predicate(&self) -> Option<&DirectPredicatePlan> {
match self {
Self::Empty => None,
Self::User(program) => program.selected_predicate(),
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct SymbolProgramTable {
slots: Vec<SymbolProgram>,
register_layout: RegisterLayout,
}
impl SymbolProgramTable {
pub(crate) fn try_new(
programs: Vec<UserSymbolProgram>,
register_layout: RegisterLayout,
) -> Result<Self> {
let dense_len = programs.len().checked_add(1).ok_or_else(|| {
DataFusionError::Internal(
"MATCH_RECOGNIZE symbol table length overflow during dense binding"
.to_string(),
)
})?;
let mut slots = Vec::with_capacity(dense_len);
slots.push(SymbolProgram::Empty);
for mut program in programs {
if program.id().index() != slots.len() {
return internal_err!(
"MATCH_RECOGNIZE symbol program {} is out of order at dense slot {}",
program.id(),
slots.len()
);
}
if program.mode() != SymbolEvalMode::Incremental {
program.selected_predicate = None;
}
slots.push(SymbolProgram::User(program));
}
Ok(Self {
slots,
register_layout,
})
}
#[cfg(test)]
pub(crate) fn test_local_predicate_ids(&self) -> Vec<SymbolId> {
self.slots
.iter()
.filter_map(|slot| match slot {
SymbolProgram::User(program) if program.local_predicate().is_some() => {
Some(program.id())
}
SymbolProgram::Empty | SymbolProgram::User(_) => None,
})
.collect()
}
pub(crate) fn predicate_route_tag(
&self,
id: SymbolId,
outcome: &RoutedPredicate,
) -> Option<&'static str> {
let SymbolProgram::User(program) = self.slots.get(id.index())? else {
return None;
};
if program.mode() != SymbolEvalMode::Incremental {
return None;
}
match outcome {
RoutedPredicate::Direct(_) if program.selected_predicate().is_some() => {
outcome.route_tag()
}
RoutedPredicate::Direct(_) | RoutedPredicate::NotApplicable => None,
RoutedPredicate::Rejected(_) => outcome.route_tag(),
}
}
#[cfg(test)]
pub(crate) fn has_selected_predicate(&self, id: SymbolId) -> bool {
matches!(
self.slots.get(id.index()),
Some(SymbolProgram::User(program))
if program.selected_predicate().is_some()
)
}
pub(crate) fn required_static_input_prefixes(&self) -> (usize, usize) {
let mut predicate_prefix = 0;
let mut scalar_prefix = 0;
for source in self
.slots
.iter()
.filter_map(SymbolProgram::selected_predicate)
.flat_map(DirectPredicatePlan::sources)
{
match source {
VmSourceRef::StaticPredicate { bool_idx } => {
predicate_prefix = predicate_prefix.max(usize::from(*bool_idx) + 1);
}
VmSourceRef::StaticScalar { scalar_idx, .. } => {
scalar_prefix = scalar_prefix.max(usize::from(*scalar_idx) + 1);
}
_ => {}
}
}
(predicate_prefix, scalar_prefix)
}
pub(crate) fn deferred_symbol_ids(&self) -> impl Iterator<Item = SymbolId> + '_ {
self.slots.iter().filter_map(|slot| match slot {
SymbolProgram::User(program) if program.mode().requires_deferred() => {
Some(program.id())
}
SymbolProgram::Empty | SymbolProgram::User(_) => None,
})
}
pub(crate) fn into_parts(self) -> (Vec<SymbolProgram>, RegisterLayout) {
(self.slots, self.register_layout)
}
}
#[cfg(test)]
mod symbol_program_contract_tests {
use super::*;
use crate::execution::matching::predicate_test_helper;
use datafusion::physical_expr::expressions::Literal;
use datafusion::scalar::ScalarValue;
fn true_expr() -> Arc<dyn PhysicalExpr> {
Arc::new(Literal::new(ScalarValue::Boolean(Some(true))))
}
#[test]
fn selected_predicate_routes_determine_exact_static_input_prefixes() {
let boolean = || predicate_test_helper::static_boolean(7, false);
let cases = [
(
SymbolEvalMode::Incremental,
None,
predicate_test_helper::static_boolean(0, false),
Some("vm:direct-expr"),
),
(
SymbolEvalMode::Incremental,
None,
predicate_test_helper::static_boolean(3, true),
Some("vm:direct-expr"),
),
(
SymbolEvalMode::Hybrid,
Some(PhysicalHybridGuardExpr::And(
Box::new(PhysicalHybridGuardExpr::Local(true_expr())),
Box::new(PhysicalHybridGuardExpr::Unknown),
)),
boolean(),
None,
),
(
SymbolEvalMode::Hybrid,
Some(PhysicalHybridGuardExpr::Unknown),
boolean(),
None,
),
(SymbolEvalMode::Static, None, boolean(), None),
(SymbolEvalMode::Deferred, None, boolean(), None),
];
let outcomes = cases
.iter()
.map(|(_, _, candidate, tag)| {
(RoutedPredicate::Direct(candidate.clone()), *tag)
})
.collect::<Vec<_>>();
let programs = cases
.into_iter()
.enumerate()
.map(|(index, (mode, guard, candidate, _))| {
UserSymbolProgram::try_new(
SymbolId::try_new(index + 1, 8).unwrap(),
mode,
mode.uses_incremental().then(true_expr),
guard,
vec![],
mode.uses_incremental().then_some(candidate),
)
.unwrap()
})
.collect();
let table =
SymbolProgramTable::try_new(programs, RegisterLayout::empty_compact(0))
.unwrap();
assert_eq!(table.required_static_input_prefixes(), (1, 4));
let rejected = RoutedPredicate::Rejected(
crate::planning::predicate::VmCompileError::BindingFailure,
);
for (index, (outcome, tag)) in outcomes.iter().enumerate() {
let id = SymbolId::try_new(index + 1, 8).unwrap();
assert_eq!(
table.has_selected_predicate(id),
*tag == Some("vm:direct-expr")
);
assert_eq!(table.predicate_route_tag(id, outcome), *tag);
assert_eq!(
table.predicate_route_tag(id, &rejected),
tag.map(|_| "vm:fallback:binding")
);
assert_eq!(
table.predicate_route_tag(id, &RoutedPredicate::NotApplicable),
None
);
}
let (required_predicates, required_scalars) =
table.required_static_input_prefixes();
for (predicates, scalars, required, error_fragment) in [
(0, 0, (0, 0), None),
(1, 4, (required_predicates, required_scalars), None),
(
0,
4,
(required_predicates, required_scalars),
Some("static predicate bindings"),
),
(
2,
4,
(required_predicates, required_scalars),
Some("static predicate bindings"),
),
(
1,
3,
(required_predicates, required_scalars),
Some("static scalar bindings"),
),
(
1,
5,
(required_predicates, required_scalars),
Some("static scalar bindings"),
),
] {
let actual = ResolvedVmStaticInputs::try_new_for_selected_predicates(
(0..predicates)
.map(ResolvedBoolColumn::new_validated)
.collect(),
(0..scalars)
.map(|index| {
Some(ScalarColumnBinding {
column: ResolvedInputColumn::new_validated(index),
})
})
.collect(),
required.0,
required.1,
);
if let Some(fragment) = error_fragment {
let error = actual.unwrap_err();
assert!(error.to_string().contains(fragment), "{error}");
} else {
let (predicates, scalars) = actual.unwrap().into_parts();
assert_eq!((predicates.len(), scalars.len()), required);
}
}
}
}
pub(crate) struct ExecutableSymbolProgramInput {
pub(crate) automaton: Arc<CompiledAutomaton>,
pub(crate) relationships: SymbolRelationships,
pub(crate) symbol_columns: Vec<SymbolColumn>,
pub(crate) static_extractions: Vec<ResolvedStaticExtraction>,
pub(crate) vm_static_inputs: ResolvedVmStaticInputs,
pub(crate) symbol_programs: SymbolProgramTable,
}
#[derive(Clone)]
pub(crate) struct AggregateProgram {
id: AggregateId,
expression: Arc<AggregateFunctionExpr>,
input_expressions: Vec<Arc<dyn PhysicalExpr>>,
has_volatile_inputs: bool,
reads_classifier: bool,
function: AggregateFunction,
backend: ManagedAggregateBackend,
symbol_id: Option<SymbolId>,
accumulator_input_mode: AccumulatorInputMode,
counts_every_row: bool,
column: ResolvedInputColumn,
output_type: DataType,
}
impl AggregateProgram {
#[allow(clippy::too_many_arguments)]
pub(crate) fn try_new(
id: AggregateId,
expression: Arc<AggregateFunctionExpr>,
function: AggregateFunction,
backend: ManagedAggregateBackend,
accumulator_input_mode: AccumulatorInputMode,
counts_every_row: bool,
column: ResolvedInputColumn,
symbol_id: Option<SymbolId>,
input_schema: &Schema,
) -> Result<Self> {
let column_index = column.index();
let field = input_schema.fields().get(column_index).ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE managed aggregate {id} column index {column_index} is outside the validated input schema"
))
})?;
let output_type = expression.field().data_type().clone();
let schema_type = field.data_type();
if schema_type != &output_type {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE managed aggregate {id} column '{}' has schema type {schema_type}, but its physical expression produces {output_type}",
field.name()
)));
}
let expressions = expression.all_expressions();
let mut input_expressions = expressions.args;
input_expressions.extend(expressions.order_by_exprs);
let has_volatile_inputs = input_expressions.iter().any(is_volatile);
let classifier_col = crate::core::MatchMetadataColumn::Classifier.as_ref();
let expr_reads_classifier = |expr: &Arc<dyn PhysicalExpr>| {
datafusion::physical_expr::utils::collect_columns(expr)
.iter()
.any(|column| column.name() == classifier_col)
};
let reads_classifier = match accumulator_input_mode {
AccumulatorInputMode::PreviousValue => {
input_expressions.first().is_some_and(expr_reads_classifier)
|| input_expressions.get(2).is_some_and(expr_reads_classifier)
}
AccumulatorInputMode::Batch => {
input_expressions.iter().any(expr_reads_classifier)
}
};
Ok(Self {
id,
expression,
input_expressions,
has_volatile_inputs,
reads_classifier,
function,
backend,
symbol_id,
accumulator_input_mode,
counts_every_row,
column,
output_type,
})
}
pub(crate) const fn id(&self) -> AggregateId {
self.id
}
pub(crate) fn expression(&self) -> &Arc<AggregateFunctionExpr> {
&self.expression
}
pub(crate) fn input_expressions(&self) -> &[Arc<dyn PhysicalExpr>] {
&self.input_expressions
}
pub(crate) const fn has_volatile_inputs(&self) -> bool {
self.has_volatile_inputs
}
pub(crate) const fn reads_classifier(&self) -> bool {
self.reads_classifier
}
pub(crate) fn function(&self) -> &AggregateFunction {
&self.function
}
pub(crate) const fn backend(&self) -> ManagedAggregateBackend {
self.backend
}
pub(crate) const fn symbol_id(&self) -> Option<SymbolId> {
self.symbol_id
}
pub(crate) const fn accumulator_input_mode(&self) -> AccumulatorInputMode {
self.accumulator_input_mode
}
pub(crate) const fn counts_every_row(&self) -> bool {
self.counts_every_row
}
#[inline]
pub(crate) fn updates_on(&self, symbol_id: SymbolId) -> bool {
self.symbol_id.is_none_or(|scope| scope == symbol_id)
}
pub(crate) const fn column(&self) -> ResolvedInputColumn {
self.column
}
pub(crate) fn output_type(&self) -> &DataType {
&self.output_type
}
}
#[cfg(test)]
mod aggregate_program_contract_tests {
use super::*;
use datafusion::arrow::datatypes::Field;
use datafusion::functions_aggregate::first_last::first_value_udaf;
use datafusion::logical_expr::expr::{AggregateFunction, AggregateFunctionParams};
use datafusion::physical_expr::aggregate::AggregateExprBuilder;
use datafusion::physical_expr::expressions::Column;
use datafusion::physical_expr_common::sort_expr::PhysicalSortExpr;
#[test]
fn physical_expression_roots_include_aggregate_arguments_and_ordering() {
let schema = Arc::new(Schema::new(vec![
Field::new("value", DataType::Int64, true),
Field::new("ordering", DataType::Int64, false),
Field::new("managed_first", DataType::Int64, true),
]));
let argument: Arc<dyn PhysicalExpr> = Arc::new(Column::new("value", 0));
let ordering: Arc<dyn PhysicalExpr> = Arc::new(Column::new("ordering", 1));
let first = first_value_udaf();
let expression = Arc::new(
AggregateExprBuilder::new(Arc::clone(&first), vec![Arc::clone(&argument)])
.schema(Arc::clone(&schema))
.alias("managed_first")
.order_by(vec![PhysicalSortExpr {
expr: Arc::clone(&ordering),
options: Default::default(),
}])
.build()
.unwrap(),
);
let function = AggregateFunction {
func: first,
params: AggregateFunctionParams {
args: vec![],
distinct: false,
filter: None,
order_by: vec![],
null_treatment: None,
},
};
let program = AggregateProgram::try_new(
AggregateId::try_new(0, 1).unwrap(),
expression,
function,
ManagedAggregateBackend::Accumulator,
AccumulatorInputMode::Batch,
false,
ResolvedInputColumn::new_validated(2),
None,
schema.as_ref(),
)
.unwrap();
let roots = program.input_expressions();
assert_eq!(roots.len(), 2);
assert!(Arc::ptr_eq(&roots[0], &argument));
assert!(Arc::ptr_eq(&roots[1], &ordering));
}
}
pub(crate) fn validate_dense_aggregate_programs(
programs: &[AggregateProgram],
) -> Result<()> {
for (index, program) in programs.iter().enumerate() {
if program.id().index() != index {
return Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE aggregate program id {} is stored at dense position {index}",
program.id()
)));
}
}
Ok(())
}
pub(crate) struct ExecutableMatchProgramInput {
pub(crate) input_schema: SchemaRef,
pub(crate) normalized_pattern: NormalizedPattern,
pub(crate) max_define_lookahead_rows: crate::core::NavigationOffset,
pub(crate) has_deferred_history_operations: bool,
pub(crate) symbols: ExecutableSymbolProgramInput,
pub(crate) aggregate_programs: Vec<AggregateProgram>,
pub(crate) output: Arc<ExecutableOutputPlan>,
pub(crate) after_match_skip: ResolvedAfterMatchSkip,
pub(crate) deferred_evaluator_factory: Option<Arc<DeferredEvaluatorFactory>>,
}
#[cfg(test)]
impl ExecutableMatchProgramInput {
pub(crate) fn replace_output(
&mut self,
spec: MatchRecognizeOutputSpec,
ids: Arc<[SymbolId]>,
) {
self.replace_output_rows(spec, ids, self.output.rows_per_match().clone());
}
pub(crate) fn replace_output_rows(
&mut self,
spec: MatchRecognizeOutputSpec,
ids: Arc<[SymbolId]>,
rows_per_match: RowsPerMatch,
) {
self.output = ExecutableOutputPlan::try_rows(
self.input_schema.as_ref(),
spec,
ids,
rows_per_match,
self.symbols.automaton.as_ref(),
)
.expect("test output must be valid");
}
pub(crate) fn set_rows_per_match(&mut self, rows_per_match: RowsPerMatch) {
self.replace_output_rows(
self.output.spec().clone(),
Arc::clone(self.output.classifier_bitset_symbol_ids()),
rows_per_match,
);
}
}
#[cfg(test)]
mod guard_tests {
use datafusion::common::Result;
use datafusion::physical_expr::PhysicalExpr;
use std::sync::Arc;
type Truth = Option<bool>;
const T: Truth = Some(true);
const F: Truth = Some(false);
const U: Truth = None;
fn evaluate(
guard: &Guard,
local: &mut impl FnMut(&Arc<dyn PhysicalExpr>) -> Result<Truth>,
) -> Result<Truth> {
guard.evaluate_local(local)
}
use crate::execution::matching::program::contracts::PhysicalHybridGuardExpr as Guard;
use datafusion::common::ScalarValue;
use datafusion::physical_plan::expressions::Literal;
fn guard(value: Truth) -> Guard {
match value {
None => Guard::Unknown,
Some(_) => Guard::Local(Arc::new(Literal::new(ScalarValue::Boolean(value)))),
}
}
#[test]
fn physical_guards_apply_kleene_logic() {
for (left, right, and, or) in [
(T, U, U, T),
(F, U, F, U),
(U, F, F, U),
(U, T, U, T),
(U, U, U, U),
(T, F, F, T),
] {
for (expression, expected) in [
(
Guard::And(Box::new(guard(left)), Box::new(guard(right))),
and,
),
(Guard::Or(Box::new(guard(left)), Box::new(guard(right))), or),
] {
let actual = evaluate(&expression, &mut |expr| {
let literal = expr.downcast_ref::<Literal>().unwrap();
match literal.value() {
ScalarValue::Boolean(Some(value)) => Ok(Some(*value)),
value => panic!("unexpected guard literal {value:?}"),
}
})
.unwrap();
assert_eq!(actual, expected, "{expression:?}");
}
}
for (value, expected) in [(T, F), (F, T), (U, U)] {
let expression = Guard::Not(Box::new(guard(value)));
assert_eq!(
evaluate(&expression, &mut |_| Ok(Some(value == T))).unwrap(),
expected
);
}
}
#[test]
fn nullable_local_leaves_do_not_make_negation_conclusive() {
let local_null =
|| Guard::Local(Arc::new(Literal::new(ScalarValue::Boolean(None))));
for expression in [
local_null(),
Guard::Not(Box::new(local_null())),
Guard::Or(
Box::new(Guard::Not(Box::new(local_null()))),
Box::new(Guard::Unknown),
),
Guard::Not(Box::new(Guard::And(
Box::new(local_null()),
Box::new(Guard::Unknown),
))),
] {
let actual = evaluate(&expression, &mut |expr| {
let literal = expr.downcast_ref::<Literal>().unwrap();
match literal.value() {
ScalarValue::Boolean(value) => Ok(*value),
value => panic!("unexpected guard literal {value:?}"),
}
})
.unwrap();
assert_eq!(actual, None, "{expression:?}");
}
}
#[test]
fn decisive_left_guards_do_not_evaluate_the_right_local_leaf() {
for (expression, expected) in [
(Guard::And(Box::new(guard(F)), Box::new(guard(T))), F),
(Guard::Or(Box::new(guard(T)), Box::new(guard(F))), T),
] {
let mut calls = 0;
assert_eq!(
evaluate(&expression, &mut |expr| {
calls += 1;
assert_eq!(calls, 1, "short-circuited right leaf was evaluated");
let literal = expr.downcast_ref::<Literal>().unwrap();
match literal.value() {
ScalarValue::Boolean(value) => Ok(*value),
value => panic!("unexpected guard literal {value:?}"),
}
})
.unwrap(),
expected
);
assert_eq!(calls, 1);
}
}
}