use super::ExtractionKind;
pub use super::output::{LogicalMatchOutput, LogicalSelectedMatchSummary};
#[cfg(test)]
use crate::core::SymbolEvalMode;
use crate::core::{
AfterMatchSkip, AggregateId, MatchMetadataColumn, MatchRecognizeOutputSpec,
MatchRecognizeSpec, Pattern, RowsPerMatch, classifier_bits_col_name,
managed_aggregate_col_name, static_predicate_and_col_name,
static_predicate_or_col_name, static_scalar_col_name, symbol_col_name,
};
use crate::planning::hybrid_guard::{LogicalHybridGuardExpr, build_logical_hybrid_guard};
use crate::planning::semantic_metadata::{
aggregate_references_semantic_metadata, is_managed_classifier_navigation_aggregate,
};
use crate::planning::{NamedExpr, SymbolRelationships};
use datafusion::arrow::datatypes::DataType;
use datafusion::common::float_semantics::has_float_leaf;
use datafusion::common::{DFSchema, Result, ScalarValue, plan_err};
use datafusion::logical_expr::expr::AggregateFunction;
use datafusion::logical_expr::{Expr, ExprSchemable, SortExpr, lit};
use std::collections::{BTreeMap, BTreeSet};
#[derive(Clone, Debug)]
pub struct LogicalSymbolInput {
pub(crate) name: String,
predicate: LogicalSymbolInputPredicate,
}
#[derive(Clone, Debug)]
enum LogicalSymbolInputPredicate {
Static { expr: Expr, demanded: bool },
MatchAware(MatchAwareSymbolInput),
}
impl LogicalSymbolInput {
pub fn static_(name: impl Into<String>, expr: Expr) -> Self {
Self {
name: name.into(),
predicate: LogicalSymbolInputPredicate::Static {
expr,
demanded: false,
},
}
}
}
impl LogicalSymbolInput {
pub(crate) fn demanded(name: impl Into<String>, expr: Expr) -> Self {
Self {
name: name.into(),
predicate: LogicalSymbolInputPredicate::Static {
expr,
demanded: true,
},
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum LogicalSymbolPredicate {
Static {
expr: Expr,
},
MatchAware(Box<MatchAwareSymbolPredicate>),
}
impl LogicalSymbolPredicate {
pub fn static_expr(&self) -> Option<&Expr> {
match self {
Self::Static { expr } => Some(expr),
Self::MatchAware(_) => None,
}
}
fn precomputed_expr(&self) -> Option<Expr> {
match self {
Self::Static { expr } => Some(expr.clone()),
Self::MatchAware(predicate) => predicate.precomputed_expr(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LogicalSymbol {
pub(super) id: LogicalSymbolId,
pub(super) name: String,
pub(super) predicate: LogicalSymbolPredicate,
demanded: bool,
}
impl LogicalSymbol {
pub fn demanded_expr(&self) -> Option<&Expr> {
if self.demanded {
self.predicate.static_expr()
} else {
None
}
}
pub const fn id(&self) -> LogicalSymbolId {
self.id
}
pub fn name(&self) -> &str {
&self.name
}
pub fn predicate(&self) -> &LogicalSymbolPredicate {
&self.predicate
}
pub fn result_column_name(&self) -> String {
symbol_col_name(self.name())
}
}
#[derive(Clone, Debug)]
pub struct LogicalMatchProgramInput {
pub partition_by: Vec<Expr>,
pub order_by: Vec<SortExpr>,
pub after_skip: AfterMatchSkip,
pub pattern: Pattern,
pub symbols: Vec<LogicalSymbolInput>,
pub match_aware: Option<ExecutableMatchProgramInput>,
pub output: LogicalMatchOutput,
pub symbol_relationships: SymbolRelationships,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LogicalMatchProgram {
partition_by: Vec<Expr>,
order_by: Vec<SortExpr>,
after_skip: AfterMatchSkip,
pattern: Pattern,
pub(super) symbols: Vec<LogicalSymbol>,
after_skip_target: Option<LogicalSymbolId>,
matcher_input_slots: Vec<InternalSlotRequirement>,
output: LogicalMatchOutput,
symbol_relationships: SymbolRelationships,
match_aware: Option<Box<ExecutableMatchProgram>>,
}
impl LogicalMatchProgram {
pub(crate) fn try_new(input: LogicalMatchProgramInput) -> Result<Self> {
let names = input
.symbols
.iter()
.map(|symbol| symbol.name.clone())
.collect::<Vec<_>>();
let after_skip_target = validate_structure(
&names,
&input.pattern,
&input.after_skip,
&input.output,
&input.symbol_relationships,
)?;
let pattern_vars = names.iter().cloned().collect::<BTreeSet<_>>();
let admission =
MatchAwareAdmission::try_new(names, &input.symbols, input.match_aware)?;
let symbols = input
.symbols
.into_iter()
.enumerate()
.map(|(index, symbol)| {
let id = LogicalSymbolId(index);
let (predicate, demanded) = match symbol.predicate {
LogicalSymbolInputPredicate::Static { expr, demanded } => {
crate::planning::define::validate_static_predicate(
&symbol.name,
&expr,
&pattern_vars,
)?;
(LogicalSymbolPredicate::Static { expr }, demanded)
}
LogicalSymbolInputPredicate::MatchAware(predicate) => (
LogicalSymbolPredicate::MatchAware(Box::new(
admission.build_predicate(id, &symbol.name, predicate)?,
)),
false,
),
};
Ok(LogicalSymbol {
id,
name: symbol.name,
predicate,
demanded,
})
})
.collect::<Result<Vec<_>>>()?;
Ok(Self {
partition_by: input.partition_by,
order_by: input.order_by,
after_skip: input.after_skip,
pattern: input.pattern,
symbols,
after_skip_target,
matcher_input_slots: Vec::new(),
output: input.output,
symbol_relationships: input.symbol_relationships,
match_aware: admission.into_payload(),
})
}
#[cfg(test)]
pub fn requires_match_aware_defines(&self) -> bool {
self.match_aware.is_some()
}
pub fn partition_by(&self) -> &[Expr] {
&self.partition_by
}
pub fn has_float_partition_keys(&self, schema: &DFSchema) -> Result<bool> {
for key in &self.partition_by {
if has_float_leaf(&key.get_type(schema)?) {
return Ok(true);
}
}
Ok(false)
}
pub fn order_by(&self) -> &[SortExpr] {
&self.order_by
}
pub fn after_skip(&self) -> &AfterMatchSkip {
&self.after_skip
}
pub fn after_skip_target(&self) -> Option<LogicalSymbolId> {
self.after_skip_target
}
pub fn rows_per_match(&self) -> &RowsPerMatch {
self.output.rows_per_match()
}
pub fn pattern(&self) -> &Pattern {
&self.pattern
}
pub fn symbols(&self) -> &[LogicalSymbol] {
&self.symbols
}
pub fn symbol_names(&self) -> impl ExactSizeIterator<Item = &str> {
self.symbols.iter().map(LogicalSymbol::name)
}
pub fn matcher_input_slots(&self) -> &[InternalSlotRequirement] {
&self.matcher_input_slots
}
pub fn internal_slot_name(&self, owner: InternalSlotOwner) -> Option<String> {
match owner {
InternalSlotOwner::SymbolResult(id) => self
.symbols
.get(id.index())
.map(LogicalSymbol::result_column_name),
other => self
.match_aware
.as_deref()
.and_then(|payload| payload.internal_slot_name(other)),
}
}
pub(crate) fn with_matcher_input_slots(mut self, schema: &DFSchema) -> Result<Self> {
let mut slots = Vec::new();
if let Some(payload) = &self.match_aware {
payload.append_matcher_input_slots(schema, &mut slots)?;
}
for symbol in &self.symbols {
let name = symbol.result_column_name();
let Some(field) = exact_internal_field(schema, &name)? else {
if symbol.predicate.static_expr().is_some() {
return plan_err!(
"MATCH_RECOGNIZE static symbol result '{name}' must bind exactly one non-null Boolean input field"
);
}
continue;
};
if field.data_type() != &DataType::Boolean || field.is_nullable() {
return plan_err!(
"MATCH_RECOGNIZE symbol result '{name}' must be non-null Boolean"
);
}
slots.push(InternalSlotRequirement::new(
InternalSlotOwner::SymbolResult(symbol.id),
DataType::Boolean,
false,
));
}
self.matcher_input_slots = slots;
Ok(self)
}
pub(crate) fn with_pruned_selected_summary_input(
mut self,
schema: &DFSchema,
) -> Result<Self> {
self.output.prune_selected_summary_input(schema)?;
Ok(self)
}
pub fn output_spec(&self) -> &MatchRecognizeOutputSpec {
self.output.spec()
}
pub fn output(&self) -> &LogicalMatchOutput {
&self.output
}
pub fn selected_match_summaries(&self) -> &[LogicalSelectedMatchSummary] {
self.output.selected_match_summaries()
}
pub fn selected_match_summary_input_spec(&self) -> Option<&MatchRecognizeOutputSpec> {
self.output.selected_match_summary_input_spec()
}
pub fn symbol_relationships(&self) -> &SymbolRelationships {
&self.symbol_relationships
}
pub(crate) fn static_defines(&self) -> impl Iterator<Item = NamedExpr> + '_ {
self.symbols.iter().filter_map(|symbol| {
symbol.predicate.precomputed_expr().map(|expr| NamedExpr {
name: symbol.name.clone(),
expr,
})
})
}
}
fn exact_internal_field<'a>(
schema: &'a DFSchema,
name: &str,
) -> Result<Option<&'a datafusion::arrow::datatypes::Field>> {
let mut fields = schema.fields().iter().filter(|field| field.name() == name);
let Some(field) = fields.next() else {
return Ok(None);
};
if fields.next().is_some() {
return plan_err!("MATCH_RECOGNIZE internal field '{name}' is ambiguous");
}
Ok(Some(field.as_ref()))
}
#[derive(Clone, Debug)]
pub(super) enum MatchAwareSymbolInput {
Local(Expr),
History { expr: Expr, local: Option<Expr> },
}
impl LogicalSymbolInputPredicate {
fn requires_history(&self) -> bool {
matches!(
self,
Self::MatchAware(MatchAwareSymbolInput::History { .. })
)
}
}
impl LogicalSymbolInput {
fn match_aware(name: impl Into<String>, predicate: MatchAwareSymbolInput) -> Self {
Self {
name: name.into(),
predicate: LogicalSymbolInputPredicate::MatchAware(predicate),
}
}
pub fn incremental(name: impl Into<String>, expr: Expr) -> Self {
Self::match_aware(name, MatchAwareSymbolInput::Local(expr))
}
pub fn deferred(name: impl Into<String>, expr: Expr) -> Self {
Self::history(name, expr, None)
}
pub fn hybrid(name: impl Into<String>, local: Expr, deferred: Expr) -> Self {
Self::history(name, deferred, Some(local))
}
pub(in crate::planning::logical) fn history(
name: impl Into<String>,
expr: Expr,
local: Option<Expr>,
) -> Self {
Self::match_aware(name, MatchAwareSymbolInput::History { expr, local })
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum MatchAwareSymbolPredicate {
Incremental {
expr: Expr,
},
Deferred {
expr: Expr,
},
Hybrid {
local: Expr,
deferred: Expr,
guard: Box<LogicalHybridGuardExpr>,
},
}
impl MatchAwareSymbolPredicate {
#[cfg(test)]
pub const fn mode(&self) -> SymbolEvalMode {
match self {
Self::Incremental { .. } => SymbolEvalMode::Incremental,
Self::Deferred { .. } => SymbolEvalMode::Deferred,
Self::Hybrid { .. } => SymbolEvalMode::Hybrid,
}
}
pub fn local_expr(&self) -> Option<&Expr> {
match self {
Self::Incremental { expr } | Self::Hybrid { local: expr, .. } => Some(expr),
Self::Deferred { .. } => None,
}
}
pub fn deferred_expr(&self) -> Option<&Expr> {
match self {
Self::Deferred { expr } | Self::Hybrid { deferred: expr, .. } => Some(expr),
Self::Incremental { .. } => None,
}
}
pub fn hybrid_guard(&self) -> Option<&LogicalHybridGuardExpr> {
match self {
Self::Hybrid { guard, .. } => Some(guard),
_ => None,
}
}
pub(super) fn precomputed_expr(&self) -> Option<Expr> {
matches!(self, Self::Deferred { .. }).then(|| lit(true))
}
}
impl LogicalSymbolPredicate {
#[cfg(test)]
pub const fn mode(&self) -> SymbolEvalMode {
match self {
Self::Static { .. } => SymbolEvalMode::Static,
Self::MatchAware(predicate) => predicate.mode(),
}
}
pub fn local_expr(&self) -> Option<&Expr> {
match self {
Self::MatchAware(predicate) => predicate.local_expr(),
Self::Static { .. } => None,
}
}
pub fn deferred_expr(&self) -> Option<&Expr> {
match self {
Self::MatchAware(predicate) => predicate.deferred_expr(),
Self::Static { .. } => None,
}
}
pub fn hybrid_guard(&self) -> Option<&LogicalHybridGuardExpr> {
match self {
Self::MatchAware(predicate) => predicate.hybrid_guard(),
Self::Static { .. } => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StaticExtractionId(usize);
impl StaticExtractionId {
pub const fn index(self) -> usize {
self.0
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LogicalStaticExtraction {
id: StaticExtractionId,
ordinal: usize,
expr: Expr,
kind: ExtractionKind,
symbols: Vec<LogicalSymbolId>,
}
impl LogicalStaticExtraction {
pub const fn id(&self) -> StaticExtractionId {
self.id
}
pub fn column_name(&self) -> String {
static_extraction_column_name(self.kind, self.ordinal)
}
pub fn expr(&self) -> &Expr {
&self.expr
}
pub const fn kind(&self) -> ExtractionKind {
self.kind
}
pub fn symbols(&self) -> &[LogicalSymbolId] {
&self.symbols
}
pub(crate) fn to_input(&self, symbols: &[LogicalSymbol]) -> StaticExtractionInput {
StaticExtractionInput {
expr: self.expr.clone(),
kind: self.kind,
symbols: self
.symbols
.iter()
.map(|id| symbols[id.index()].name.clone())
.collect(),
}
}
}
#[derive(Clone, Debug)]
pub struct StaticExtractionInput {
expr: Expr,
kind: ExtractionKind,
symbols: Vec<String>,
}
impl StaticExtractionInput {
pub fn new(expr: Expr, kind: ExtractionKind, symbols: Vec<String>) -> Self {
Self {
expr,
kind,
symbols,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct LogicalManagedAggregate {
id: AggregateId,
func: AggregateFunction,
symbol: Option<LogicalSymbolId>,
}
impl LogicalManagedAggregate {
#[cfg(test)]
pub(crate) fn for_test(
id: usize,
func: AggregateFunction,
symbol: Option<LogicalSymbolId>,
) -> Self {
Self {
id: AggregateId::try_new(id, id + 1).expect("test aggregate ID is valid"),
func,
symbol,
}
}
pub const fn id(&self) -> AggregateId {
self.id
}
pub fn func(&self) -> &AggregateFunction {
&self.func
}
pub const fn symbol(&self) -> Option<LogicalSymbolId> {
self.symbol
}
pub fn column_name(&self) -> String {
managed_aggregate_col_name(self.id.index())
}
pub(crate) fn to_input(&self, symbols: &[LogicalSymbol]) -> ManagedAggregateInput {
ManagedAggregateInput {
func: self.func.clone(),
symbol: self.symbol.map(|id| symbols[id.index()].name.clone()),
}
}
}
#[derive(Clone, Debug)]
pub struct ManagedAggregateInput {
func: AggregateFunction,
symbol: Option<String>,
}
impl ManagedAggregateInput {
pub fn new(func: AggregateFunction, symbol: Option<String>) -> Self {
Self { func, symbol }
}
pub(crate) fn replace_func(&mut self, func: AggregateFunction) {
self.func = func;
}
}
#[derive(Clone, Debug)]
pub struct ExecutableMatchProgramInput {
pub static_extractions: Vec<StaticExtractionInput>,
pub managed_aggregates: Vec<ManagedAggregateInput>,
}
impl ExecutableMatchProgramInput {
pub fn new(
static_extractions: Vec<StaticExtractionInput>,
managed_aggregates: Vec<ManagedAggregateInput>,
) -> Option<Self> {
(!static_extractions.is_empty() || !managed_aggregates.is_empty()).then_some(
Self {
static_extractions,
managed_aggregates,
},
)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ExecutableMatchProgram {
static_extractions: Vec<LogicalStaticExtraction>,
managed_aggregates: Vec<LogicalManagedAggregate>,
}
impl ExecutableMatchProgram {
pub fn static_extractions(&self) -> &[LogicalStaticExtraction] {
&self.static_extractions
}
pub fn managed_aggregates(&self) -> &[LogicalManagedAggregate] {
&self.managed_aggregates
}
pub(super) fn internal_slot_name(&self, owner: InternalSlotOwner) -> Option<String> {
match owner {
InternalSlotOwner::ManagedAggregate(id) => self
.managed_aggregates
.get(id.index())
.map(|_| managed_aggregate_col_name(id.index())),
InternalSlotOwner::StaticExtraction(id) => self
.static_extractions
.get(id.index())
.map(LogicalStaticExtraction::column_name),
InternalSlotOwner::SymbolResult(_) => None,
}
}
pub(super) fn append_matcher_input_slots(
&self,
schema: &DFSchema,
slots: &mut Vec<InternalSlotRequirement>,
) -> Result<()> {
for extraction in &self.static_extractions {
let name = extraction.column_name();
let field = required_internal_field(schema, &name)?;
if extraction.kind() != ExtractionKind::Scalar
&& field.data_type() != &DataType::Boolean
{
return plan_err!(
"MATCH_RECOGNIZE static extraction '{}' must be Boolean, got {}",
field.name(),
field.data_type()
);
}
slots.push(InternalSlotRequirement::new(
InternalSlotOwner::StaticExtraction(extraction.id()),
field.data_type().clone(),
field.is_nullable(),
));
}
for aggregate in &self.managed_aggregates {
let name = aggregate.column_name();
let field = required_internal_field(schema, &name)?;
slots.push(InternalSlotRequirement::new(
InternalSlotOwner::ManagedAggregate(aggregate.id()),
field.data_type().clone(),
field.is_nullable(),
));
}
Ok(())
}
}
impl LogicalMatchProgram {
pub fn can_skip_candidate_evaluation(&self, input_schema: &DFSchema) -> bool {
use crate::planning::expr_safety::can_discard_scalar;
let safe = |expr: &Expr| can_discard_scalar(expr, Some(input_schema));
self.symbols()
.iter()
.all(|symbol| match symbol.predicate() {
LogicalSymbolPredicate::Static { .. } => symbol.demanded_expr().is_none(),
LogicalSymbolPredicate::MatchAware(predicate) => {
predicate.deferred_expr().is_none()
&& predicate.local_expr().is_some_and(safe)
}
})
&& self.managed_aggregates().iter().all(|aggregate| {
managed_aggregate_is_infallible(aggregate.func(), input_schema, &safe)
})
}
pub fn match_aware(&self) -> Option<&ExecutableMatchProgram> {
self.match_aware.as_deref()
}
pub fn static_extractions(&self) -> &[LogicalStaticExtraction] {
self.match_aware()
.map(ExecutableMatchProgram::static_extractions)
.unwrap_or_default()
}
pub fn managed_aggregates(&self) -> &[LogicalManagedAggregate] {
self.match_aware()
.map(ExecutableMatchProgram::managed_aggregates)
.unwrap_or_default()
}
}
struct SymbolCatalog {
names: Vec<String>,
requires_history: Vec<bool>,
}
impl SymbolCatalog {
fn new(names: Vec<String>, symbols: &[LogicalSymbolInput]) -> Self {
let requires_history = symbols
.iter()
.map(|symbol| symbol.predicate.requires_history())
.collect();
Self {
names,
requires_history,
}
}
fn id(&self, context: &str, name: &str) -> Result<LogicalSymbolId> {
resolve_symbol(&self.names, context, name)
}
}
pub(super) struct MatchAwareAdmission {
catalog: SymbolCatalog,
payload: Option<Box<ExecutableMatchProgram>>,
}
impl MatchAwareAdmission {
pub(super) fn try_new(
names: Vec<String>,
symbols: &[LogicalSymbolInput],
input: Option<ExecutableMatchProgramInput>,
) -> Result<Self> {
let catalog = SymbolCatalog::new(names, symbols);
let input = input.unwrap_or_else(|| ExecutableMatchProgramInput {
static_extractions: vec![],
managed_aggregates: vec![],
});
let managed_aggregates =
build_managed_aggregates(input.managed_aggregates, &catalog)?;
let mut ordinals = [0; 3];
let static_extractions = input
.static_extractions
.into_iter()
.enumerate()
.map(|(index, extraction)| {
let kind_index = match extraction.kind {
ExtractionKind::BooleanAnd => 0,
ExtractionKind::BooleanOr => 1,
ExtractionKind::Scalar => 2,
};
let ordinal = ordinals[kind_index];
ordinals[kind_index] += 1;
Ok(LogicalStaticExtraction {
id: StaticExtractionId(index),
ordinal,
expr: extraction.expr,
kind: extraction.kind,
symbols: extraction
.symbols
.iter()
.map(|name| catalog.id("static extraction", name))
.collect::<Result<Vec<_>>>()?,
})
})
.collect::<Result<Vec<_>>>()?;
let candidate_predicates = symbols.iter().any(|symbol| {
matches!(symbol.predicate, LogicalSymbolInputPredicate::MatchAware(_))
});
let payload = (candidate_predicates
|| !static_extractions.is_empty()
|| !managed_aggregates.is_empty())
.then(|| {
Box::new(ExecutableMatchProgram {
static_extractions,
managed_aggregates,
})
});
Ok(Self { catalog, payload })
}
pub(super) fn build_predicate(
&self,
id: LogicalSymbolId,
name: &str,
input: MatchAwareSymbolInput,
) -> Result<MatchAwareSymbolPredicate> {
Ok(match input {
MatchAwareSymbolInput::Local(expr) => {
MatchAwareSymbolPredicate::Incremental { expr }
}
MatchAwareSymbolInput::History { expr, local: None } => {
MatchAwareSymbolPredicate::Deferred { expr }
}
MatchAwareSymbolInput::History {
expr: deferred,
local: Some(local),
} => {
let aggregates = self
.payload
.as_deref()
.map(ExecutableMatchProgram::managed_aggregates)
.unwrap_or_default();
let columns = effective_deferred_columns(id, aggregates, &self.catalog);
let guard = build_logical_hybrid_guard(&local, &columns);
if !guard.contains_unknown() {
return plan_err!(
"MATCH_RECOGNIZE Hybrid symbol '{}' has no Deferred dependency",
name
);
}
MatchAwareSymbolPredicate::Hybrid {
local,
deferred,
guard: Box::new(guard),
}
}
})
}
pub(super) fn into_payload(self) -> Option<Box<ExecutableMatchProgram>> {
self.payload
}
}
fn static_extraction_column_name(kind: ExtractionKind, ordinal: usize) -> String {
match kind {
ExtractionKind::BooleanAnd => static_predicate_and_col_name(ordinal),
ExtractionKind::BooleanOr => static_predicate_or_col_name(ordinal),
ExtractionKind::Scalar => static_scalar_col_name(ordinal),
}
}
fn build_managed_aggregates(
inputs: Vec<ManagedAggregateInput>,
catalog: &SymbolCatalog,
) -> Result<Vec<LogicalManagedAggregate>> {
let count = inputs.len();
inputs
.into_iter()
.enumerate()
.map(|(index, aggregate)| {
if aggregate_references_semantic_metadata(&aggregate.func)
&& !is_managed_classifier_navigation_aggregate(&aggregate.func)
{
return plan_err!(
"MATCH_RECOGNIZE managed aggregate {index} cannot read match metadata in a semantic argument, filter, or ordering expression"
);
}
if aggregate.func.params.filter.is_some() {
return plan_err!(
"MATCH_RECOGNIZE managed aggregate {index} cannot retain FILTER; normalize it before constructing managed state"
);
}
Ok(LogicalManagedAggregate {
id: AggregateId::try_new(index, count)
.expect("validated aggregate position is in bounds"),
func: aggregate.func,
symbol: aggregate
.symbol
.as_deref()
.map(|symbol| catalog.id("managed aggregate", symbol))
.transpose()?,
})
})
.collect()
}
fn required_internal_field<'a>(
schema: &'a DFSchema,
name: &str,
) -> Result<&'a datafusion::arrow::datatypes::Field> {
exact_internal_field(schema, name)?.ok_or_else(|| {
datafusion::common::DataFusionError::Plan(format!(
"MATCH_RECOGNIZE internal field '{name}' is missing"
))
})
}
pub(in crate::planning::logical) fn effective_deferred_columns_for_program(
program: &LogicalMatchProgram,
define_id: LogicalSymbolId,
) -> BTreeSet<String> {
collect_effective_deferred_columns(
define_id,
program.managed_aggregates(),
program.symbol_names(),
|source| {
program.symbols()[source.index()]
.predicate()
.deferred_expr()
.is_some()
},
)
}
fn effective_deferred_columns(
define_id: LogicalSymbolId,
aggregates: &[LogicalManagedAggregate],
catalog: &SymbolCatalog,
) -> BTreeSet<String> {
collect_effective_deferred_columns(
define_id,
aggregates,
catalog.names.iter().map(String::as_str),
|source| catalog.requires_history[source.index()],
)
}
fn collect_effective_deferred_columns<'a>(
define_id: LogicalSymbolId,
aggregates: &[LogicalManagedAggregate],
symbol_names: impl IntoIterator<Item = &'a str>,
requires_history: impl Fn(LogicalSymbolId) -> bool,
) -> BTreeSet<String> {
symbol_names
.into_iter()
.map(classifier_bits_col_name)
.chain(aggregates.iter().filter_map(|aggregate| {
let source = aggregate.symbol()?;
(source != define_id && requires_history(source))
.then(|| aggregate.column_name())
}))
.collect()
}
pub(crate) fn managed_aggregate_is_infallible(
func: &AggregateFunction,
input_schema: &DFSchema,
safe: &impl Fn(&Expr) -> bool,
) -> bool {
use crate::planning::expr_safety::{
scalar_ordering_type_is_safe, scalar_value_type_is_safe,
};
use datafusion::functions_aggregate::{
average::avg_udaf,
bool_and_or::{bool_and_udaf, bool_or_udaf},
count::count_udaf,
first_last::{first_value_udaf, last_value_udaf},
min_max::{max_udaf, min_udaf},
stddev::{stddev_pop_udaf, stddev_udaf},
sum::sum_udaf,
variance::{var_pop_udaf, var_samp_udaf},
};
use datafusion::logical_expr::type_coercion::functions::fields_with_udf;
use datafusion::logical_expr::{ExprSchemable, Volatility};
if !crate::planning::extract::is_plain_aggregate(func)
|| func.func.signature().volatility != Volatility::Immutable
|| !func.params.args.iter().all(safe)
{
return false;
}
let udaf = func.func.as_ref();
if udaf == count_udaf().as_ref() {
return func.params.args.len() <= 1;
}
if udaf == crate::functions::udaf::mr_prev_udaf().as_ref() {
let [
value,
Expr::Literal(ScalarValue::UInt64(Some(0)), _),
Expr::Literal(default, _),
matched,
classifier,
] = func.params.args.as_slice()
else {
return false;
};
return value.get_type(input_schema).is_ok_and(|ty| {
scalar_ordering_type_is_safe(&ty) && default.data_type() == ty
}) && matched
.get_type(input_schema)
.is_ok_and(|ty| ty == DataType::Boolean)
&& classifier
.get_type(input_schema)
.is_ok_and(|ty| ty == DataType::Boolean);
}
let [arg] = func.params.args.as_slice() else {
return false;
};
let Ok((_, arg_field)) = arg.to_field(input_schema) else {
return false;
};
let Ok(coerced_fields) = fields_with_udf(std::slice::from_ref(&arg_field), udaf)
else {
return false;
};
let [coerced_field] = coerced_fields.as_slice() else {
return false;
};
if arg_field.data_type() != coerced_field.data_type() {
return false;
}
let Ok(return_field) = func.func.return_field(&coerced_fields) else {
return false;
};
let coerced_type = coerced_field.data_type();
let return_type = return_field.data_type();
if udaf == first_value_udaf().as_ref() || udaf == last_value_udaf().as_ref() {
return scalar_value_type_is_safe(coerced_type) && return_type == coerced_type;
}
if udaf == min_udaf().as_ref() || udaf == max_udaf().as_ref() {
return !coerced_type.is_null()
&& scalar_ordering_type_is_safe(coerced_type)
&& return_type == coerced_type;
}
if udaf == bool_and_udaf().as_ref() || udaf == bool_or_udaf().as_ref() {
return *coerced_type == DataType::Boolean && *return_type == DataType::Boolean;
}
if udaf == sum_udaf().as_ref() {
return match (coerced_type, return_type) {
(DataType::Int64 | DataType::UInt64 | DataType::Float64, _) => {
return_type == coerced_type
}
(DataType::Decimal128(_, s), DataType::Decimal128(_, rs)) => {
s == rs
&& scalar_value_type_is_safe(coerced_type)
&& scalar_value_type_is_safe(return_type)
}
_ => false,
};
}
if udaf == avg_udaf().as_ref()
|| udaf == stddev_udaf().as_ref()
|| udaf == stddev_pop_udaf().as_ref()
|| udaf == var_samp_udaf().as_ref()
|| udaf == var_pop_udaf().as_ref()
{
return *coerced_type == DataType::Float64 && *return_type == DataType::Float64;
}
false
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LogicalSymbolId(pub(crate) usize);
impl LogicalSymbolId {
pub const fn index(self) -> usize {
self.0
}
#[cfg(test)]
pub(crate) const fn for_test(index: usize) -> Self {
Self(index)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum InternalSlotOwner {
SymbolResult(LogicalSymbolId),
ManagedAggregate(AggregateId),
StaticExtraction(StaticExtractionId),
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct InternalSlotRequirement {
owner: InternalSlotOwner,
data_type: DataType,
nullable: bool,
}
impl InternalSlotRequirement {
pub(crate) fn new(
owner: InternalSlotOwner,
data_type: DataType,
nullable: bool,
) -> Self {
Self {
owner,
data_type,
nullable,
}
}
pub const fn owner(&self) -> InternalSlotOwner {
self.owner
}
pub const fn data_type(&self) -> &DataType {
&self.data_type
}
pub const fn nullable(&self) -> bool {
self.nullable
}
}
pub(crate) fn resolve_symbol(
symbols: &[String],
context: &str,
name: &str,
) -> Result<LogicalSymbolId> {
let Some(index) = symbols
.iter()
.position(|symbol| symbol.eq_ignore_ascii_case(name))
else {
return plan_err!("MATCH_RECOGNIZE {context} references unknown symbol '{name}'");
};
if symbols[index] != name {
return plan_err!(
"MATCH_RECOGNIZE {context} must use canonical symbol '{}', not '{name}'",
symbols[index]
);
}
Ok(LogicalSymbolId(index))
}
pub(crate) fn validate_structure(
symbols: &[String],
pattern: &Pattern,
after_skip: &AfterMatchSkip,
output: &LogicalMatchOutput,
relationships: &SymbolRelationships,
) -> Result<Option<LogicalSymbolId>> {
let mut seen = BTreeMap::new();
for name in symbols {
if let Some(previous) = seen.insert(name.to_ascii_lowercase(), name) {
return plan_err!(
"MATCH_RECOGNIZE logical symbol '{name}' duplicates symbol '{previous}'"
);
}
}
if symbols.iter().cloned().collect::<BTreeSet<_>>() != pattern.symbol_names() {
return plan_err!(
"MATCH_RECOGNIZE logical program symbols do not match pattern symbols"
);
}
let target = match after_skip {
AfterMatchSkip::ToFirst(name) | AfterMatchSkip::ToLast(name) => {
Some(resolve_symbol(symbols, "AFTER MATCH SKIP", name)?)
}
_ => None,
};
for (left, right) in relationships.disjoint.iter().chain(&relationships.implies) {
resolve_symbol(symbols, "symbol relationship", left)?;
resolve_symbol(symbols, "symbol relationship", right)?;
}
let classifier_symbols = output.spec().classifier_bitset_symbols();
let classifiers = classifier_symbols
.iter()
.map(|name| resolve_symbol(symbols, "classifier output", name))
.collect::<Result<BTreeSet<_>>>()?;
if classifiers.len() != classifier_symbols.len() {
return plan_err!(
"MATCH_RECOGNIZE classifier output contains a duplicate symbol"
);
}
validate_match_output(output, symbols)?;
Ok(target)
}
pub(crate) fn validate_match_output(
output: &LogicalMatchOutput,
symbols: &[String],
) -> Result<()> {
let LogicalMatchOutput::SelectedSummaries {
spec,
input_spec,
summaries,
} = output
else {
return Ok(());
};
if input_spec.navigation_offsets() != spec.navigation_offsets() {
return plan_err!(
"MATCH_RECOGNIZE selected-match summary row selections must use the same navigation offsets"
);
}
if input_spec
.metadata_columns()
.contains(&MatchMetadataColumn::PathId)
{
return plan_err!(
"MATCH_RECOGNIZE selected-match summary input cannot select the internal path ID"
);
}
let classifier_ids = input_spec
.classifier_bitset_symbols()
.iter()
.map(|symbol| {
resolve_symbol(symbols, "selected-match summary input classifier", symbol)
})
.collect::<Result<BTreeSet<_>>>()?;
if classifier_ids.len() != input_spec.classifier_bitset_symbols().len() {
return plan_err!(
"MATCH_RECOGNIZE selected-match summary input classifier contract contains a duplicate symbol"
);
}
let mut output_ids = BTreeSet::new();
for summary in summaries {
if !output_ids.insert(summary.field().output_id()) {
return plan_err!(
"MATCH_RECOGNIZE summary output ID {} is selected more than once",
summary.field().output_id()
);
}
}
Ok(())
}
pub(crate) type LoweredMatchSpec = MatchRecognizeSpec<Expr>;
#[cfg(test)]
mod stateful_tests {
use super::*;
use datafusion::arrow::datatypes::{Field, Schema};
use datafusion::functions_aggregate::{
average::avg_udaf,
bool_and_or::{bool_and_udaf, bool_or_udaf},
count::count_udaf,
first_last::{first_value_udaf, last_value_udaf},
min_max::{max_udaf, min_udaf},
stddev::{stddev_pop_udaf, stddev_udaf},
sum::sum_udaf,
variance::{var_pop_udaf, var_samp_udaf},
};
use datafusion::logical_expr::expr::AggregateFunctionParams;
use datafusion::logical_expr::{Operator, binary_expr, col};
use std::sync::Arc;
fn test_schema() -> DFSchema {
let ree = DataType::RunEndEncoded(
Arc::new(Field::new("run_ends", DataType::Int32, false)),
Arc::new(Field::new("values", DataType::Int64, true)),
);
DFSchema::try_from(Arc::new(Schema::new(vec![
Field::new("i32_col", DataType::Int32, true),
Field::new("i64_col", DataType::Int64, true),
Field::new("u64_col", DataType::UInt64, true),
Field::new("f64_col", DataType::Float64, true),
Field::new("dec_col", DataType::Decimal128(10, 2), true),
Field::new("str_col", DataType::Utf8, true),
Field::new("bool_col", DataType::Boolean, true),
Field::new("null_col", DataType::Null, true),
Field::new("ree_col", ree.clone(), true),
Field::new(
"list_ree_col",
DataType::List(Arc::new(Field::new("item", ree, true))),
true,
),
Field::new(
"list_i64_col",
DataType::List(Arc::new(Field::new("item", DataType::Int64, true))),
true,
),
])))
.unwrap()
}
fn plain_agg(
udaf: Arc<datafusion::logical_expr::AggregateUDF>,
args: Vec<Expr>,
) -> AggregateFunction {
AggregateFunction::new_udf(udaf, args, false, None, vec![], None)
}
#[test]
fn managed_aggregate_infallibility_admits_safe_builtins_and_rejects_fallible() {
let schema = test_schema();
let safe = |expr: &Expr| {
crate::planning::expr_safety::can_discard_scalar(expr, Some(&schema))
};
for (label, agg) in [
(
"first_value",
plain_agg(first_value_udaf(), vec![col("f64_col")]),
),
(
"last_value",
plain_agg(last_value_udaf(), vec![col("dec_col")]),
),
(
"first_value(list<i64>)",
plain_agg(first_value_udaf(), vec![col("list_i64_col")]),
),
("count(*)", plain_agg(count_udaf(), vec![lit(1_i64)])),
("count(col)", plain_agg(count_udaf(), vec![col("str_col")])),
("min(f64)", plain_agg(min_udaf(), vec![col("f64_col")])),
("max(str)", plain_agg(max_udaf(), vec![col("str_col")])),
("max(dec)", plain_agg(max_udaf(), vec![col("dec_col")])),
("sum(i64)", plain_agg(sum_udaf(), vec![col("i64_col")])),
("sum(u64)", plain_agg(sum_udaf(), vec![col("u64_col")])),
("sum(f64)", plain_agg(sum_udaf(), vec![col("f64_col")])),
("sum(dec)", plain_agg(sum_udaf(), vec![col("dec_col")])),
("avg(f64)", plain_agg(avg_udaf(), vec![col("f64_col")])),
(
"bool_and",
plain_agg(bool_and_udaf(), vec![col("bool_col")]),
),
("bool_or", plain_agg(bool_or_udaf(), vec![col("bool_col")])),
(
"stddev(f64)",
plain_agg(stddev_udaf(), vec![col("f64_col")]),
),
(
"stddev_pop(f64)",
plain_agg(stddev_pop_udaf(), vec![col("f64_col")]),
),
(
"var_samp(f64)",
plain_agg(var_samp_udaf(), vec![col("f64_col")]),
),
(
"var_pop(f64)",
plain_agg(var_pop_udaf(), vec![col("f64_col")]),
),
] {
assert!(
managed_aggregate_is_infallible(&agg, &schema, &safe),
"expected infallible: {label}"
);
}
let distinct_count = AggregateFunction {
func: count_udaf(),
params: AggregateFunctionParams {
args: vec![col("i64_col")],
distinct: true,
filter: None,
order_by: vec![],
null_treatment: None,
},
};
let fallible_arg = plain_agg(
sum_udaf(),
vec![binary_expr(lit(1_i64), Operator::Divide, col("i64_col"))],
);
for (label, agg) in [
(
"uncoerced sum(i32)",
plain_agg(sum_udaf(), vec![col("i32_col")]),
),
(
"uncoerced avg(i64)",
plain_agg(avg_udaf(), vec![col("i64_col")]),
),
(
"uncoerced stddev(i64)",
plain_agg(stddev_udaf(), vec![col("i64_col")]),
),
(
"uncoerced bool_and(null)",
plain_agg(bool_and_udaf(), vec![col("null_col")]),
),
(
"first_value(ree)",
plain_agg(first_value_udaf(), vec![col("ree_col")]),
),
(
"last_value(ree)",
plain_agg(last_value_udaf(), vec![col("ree_col")]),
),
(
"first_value(list<ree>)",
plain_agg(first_value_udaf(), vec![col("list_ree_col")]),
),
("min(null)", plain_agg(min_udaf(), vec![col("null_col")])),
("max(null)", plain_agg(max_udaf(), vec![col("null_col")])),
("avg(dec)", plain_agg(avg_udaf(), vec![col("dec_col")])),
("sum(str)", plain_agg(sum_udaf(), vec![col("str_col")])),
("avg(str)", plain_agg(avg_udaf(), vec![col("str_col")])),
("count(distinct)", distinct_count),
("sum(1/i64)", fallible_arg),
] {
assert!(
!managed_aggregate_is_infallible(&agg, &schema, &safe),
"expected fallible/rejected: {label}"
);
}
}
}