use std::sync::Arc;
use crate::core::{AggregateId, MatchMetadataColumn, SymbolId};
use crate::execution::common::progress::CoarseWorkCounter;
use crate::execution::matching::program::contracts::AggregateProgram;
use crate::execution::storage::collection::BatchCollection;
use crate::planning::AccumulatorInputMode;
use datafusion::arrow::array::ArrayRef;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::{DataFusionError, Result};
use datafusion::execution::memory_pool::MemoryReservation;
use datafusion::physical_expr::expressions::{Column, Literal};
use datafusion::physical_plan::PhysicalExpr;
pub(crate) enum ValueProvider<'a> {
Row {
arguments: &'a mut [Vec<ArrayRef>],
argument_memory: &'a MemoryReservation,
programs: &'a [AggregateProgram],
cached_batch: &'a mut Option<RecordBatch>,
input: &'a BatchCollection,
location: (usize, usize),
symbol_id: Option<SymbolId>,
symbol_name_arrays: &'a [Option<ArrayRef>],
},
#[cfg(test)]
Prepared(&'a [Vec<ArrayRef>]),
}
pub(super) fn clear_argument_slot(slot: &mut Vec<ArrayRef>, memory: &MemoryReservation) {
let bytes = slot.iter().map(|array| array.get_array_memory_size()).sum();
slot.clear();
memory.shrink(bytes);
}
fn charge_argument(array: ArrayRef, memory: &MemoryReservation) -> Result<ArrayRef> {
memory.try_grow(array.get_array_memory_size())?;
Ok(array)
}
fn try_evaluate_direct_arg(
expression: &Arc<dyn PhysicalExpr>,
cached_batch: Option<&RecordBatch>,
input: &BatchCollection,
(batch_index, local_row): (usize, usize),
symbol_id: Option<SymbolId>,
symbol_name_arrays: &[Option<ArrayRef>],
argument_memory: &MemoryReservation,
) -> Option<Result<ArrayRef>> {
if let Some(column) = expression.downcast_ref::<Column>() {
if column.name() == MatchMetadataColumn::Classifier.as_ref() {
let Some(sym_id) = symbol_id else {
return Some(Err(DataFusionError::Internal(
"MATCH_RECOGNIZE classifier column evaluated without an active symbol"
.to_string(),
)));
};
let Some(array) = symbol_name_arrays
.get(sym_id.index())
.and_then(Option::as_ref)
else {
return Some(Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE classifier symbol id {} has no bound name array",
sym_id.index()
))));
};
return Some(charge_argument(Arc::clone(array), argument_memory));
}
let col_idx = column.index();
if let Some(batch) = cached_batch {
return batch
.columns()
.get(col_idx)
.map(|col| charge_argument(Arc::clone(col), argument_memory));
}
let col = input.batch(batch_index).columns().get(col_idx)?;
let sliced = col.slice(local_row, 1);
return Some(charge_argument(sliced, argument_memory));
}
if let Some(literal) = expression.downcast_ref::<Literal>() {
return Some(
literal
.value()
.to_array_of_size(1)
.and_then(|array| charge_argument(array, argument_memory)),
);
}
None
}
impl ValueProvider<'_> {
pub(crate) fn evaluate_args(
&mut self,
aggregate_id: AggregateId,
work: &mut CoarseWorkCounter,
report: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<&[ArrayRef]> {
let aggregate_index = aggregate_id.index();
let missing_slot = || {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE managed aggregate {aggregate_id} has no argument slot {aggregate_index}"
))
};
match self {
#[cfg(test)]
Self::Prepared(arguments) => arguments
.get(aggregate_index)
.map(Vec::as_slice)
.ok_or_else(missing_slot),
Self::Row {
arguments,
argument_memory,
programs,
cached_batch,
input,
location,
symbol_id,
symbol_name_arrays,
} => {
let slot = arguments
.get_mut(aggregate_index)
.ok_or_else(missing_slot)?;
let program = programs.get(aggregate_index).ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE managed aggregate {aggregate_id} has no argument program"
))
})?;
if program.has_volatile_inputs() || program.reads_classifier() {
clear_argument_slot(slot, argument_memory);
} else if !slot.is_empty() {
return Ok(slot);
}
let expressions = program.input_expressions();
let skip_prev_masks = matches!(
program.accumulator_input_mode(),
AccumulatorInputMode::PreviousValue
);
let eval_count = if skip_prev_masks {
expressions.len().min(3) + expressions.len().saturating_sub(5)
} else {
expressions.len()
};
if eval_count == 0 {
return Ok(slot);
}
slot.try_reserve_exact(eval_count).map_err(|error| {
DataFusionError::ResourcesExhausted(format!(
"MATCH_RECOGNIZE could not reserve {eval_count} arguments for aggregate {aggregate_id}: {error}",
))
})?;
let result: Result<()> = (|| {
for (idx, expression) in expressions.iter().enumerate() {
if skip_prev_masks && (idx == 3 || idx == 4) {
continue;
}
let array = if let Some(direct) = try_evaluate_direct_arg(
expression,
cached_batch.as_ref(),
input,
*location,
*symbol_id,
symbol_name_arrays,
argument_memory,
) {
direct
} else {
if cached_batch.is_none() {
work.flush_result(Ok(()), report)?;
cache_single_row_batch(
cached_batch,
input,
*location,
report,
)?;
}
let batch = cached_batch
.as_ref()
.expect("row batch must exist after materialization");
expression
.evaluate(batch)
.and_then(|value| value.into_array(batch.num_rows()))
.and_then(|array| charge_argument(array, argument_memory))
};
let accounting = work.complete_one(report);
let array = array?;
slot.push(array);
accounting?;
}
Ok(())
})();
if result.is_err() {
clear_argument_slot(slot, argument_memory);
}
result?;
Ok(slot)
}
}
}
}
pub(super) fn cache_single_row_batch(
cache: &mut Option<RecordBatch>,
input: &BatchCollection,
(batch_index, local_row): (usize, usize),
report: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<()> {
let batch = input.batch(batch_index).slice(local_row, 1);
report(batch.num_columns())?;
*cache = Some(batch);
Ok(())
}
#[cfg(test)]
mod tests {
use super::try_evaluate_direct_arg;
use crate::execution::storage::collection::BatchCollection;
use datafusion::arrow::array::{ArrayRef, Int64Array, StringArray};
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::physical_expr::expressions::{Column, Literal};
use datafusion::physical_plan::PhysicalExpr;
use datafusion::scalar::ScalarValue;
use std::sync::Arc;
#[test]
fn direct_column_and_literal_args_slice_narrowly_without_full_row_batch() {
let argument_memory =
crate::execution::common::memory::new_unbounded_state_memory().new_empty();
let mut fields = vec![Field::new("txt", DataType::Utf8, true)];
let mut columns =
vec![Arc::new(StringArray::from(vec!["a", "b", "c"])) as ArrayRef];
for i in 0..64 {
fields.push(Field::new(format!("pad_{i}"), DataType::Int64, false));
columns.push(Arc::new(Int64Array::from(vec![i, i + 1, i + 2])) as ArrayRef);
}
let schema = Arc::new(Schema::new(fields));
let batch = RecordBatch::try_new(Arc::clone(&schema), columns).unwrap();
let input = BatchCollection::try_new(vec![batch], schema).unwrap();
let col_expr: Arc<dyn PhysicalExpr> = Arc::new(Column::new("txt", 0));
let lit_expr: Arc<dyn PhysicalExpr> =
Arc::new(Literal::new(ScalarValue::Utf8(Some(",".to_string()))));
let first = try_evaluate_direct_arg(
&col_expr,
None,
&input,
(0, 1),
None,
&[],
&argument_memory,
)
.unwrap()
.unwrap();
let second = try_evaluate_direct_arg(
&col_expr,
None,
&input,
(0, 1),
None,
&[],
&argument_memory,
)
.unwrap()
.unwrap();
assert_eq!(first.to_data(), second.to_data());
assert_eq!(
first
.as_any()
.downcast_ref::<StringArray>()
.unwrap()
.value(0),
"b"
);
let delim = try_evaluate_direct_arg(
&lit_expr,
None,
&input,
(0, 1),
None,
&[],
&argument_memory,
)
.unwrap()
.unwrap();
assert_eq!(
delim
.as_any()
.downcast_ref::<StringArray>()
.unwrap()
.value(0),
","
);
}
#[test]
fn volatile_aggregate_arguments_re_evaluate_per_transition() {
use super::ValueProvider;
use crate::core::AggregateId;
use crate::execution::common::progress::CoarseWorkCounter;
use crate::execution::matching::ResolvedInputColumn;
use crate::execution::matching::program::contracts::AggregateProgram;
use crate::planning::{AccumulatorInputMode, ManagedAggregateBackend};
use datafusion::common::DFSchema;
use datafusion::functions_aggregate::count::count_udaf;
use datafusion::logical_expr::expr::{
AggregateFunction, AggregateFunctionParams,
};
use datafusion::logical_expr::{
ColumnarValue, Volatility, col, create_udf,
physical_planning_context::PhysicalPlanningContext,
};
use datafusion::physical_expr::aggregate::AggregateExprBuilder;
use datafusion::physical_expr::{
create_physical_expr, execution_props::ExecutionProps,
};
use std::sync::atomic::{AtomicI64, Ordering};
let schema = Arc::new(Schema::new(vec![
Field::new("value", DataType::Int64, false),
Field::new("agg_volatile", DataType::Int64, false),
Field::new("agg_immutable", DataType::Int64, false),
]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int64Array::from(vec![10])) as ArrayRef,
Arc::new(Int64Array::from(vec![0])) as ArrayRef,
Arc::new(Int64Array::from(vec![0])) as ArrayRef,
],
)
.unwrap();
let input = BatchCollection::try_new(vec![batch], Arc::clone(&schema)).unwrap();
let df_schema = DFSchema::try_from(schema.as_ref().clone()).unwrap();
let volatile_calls = Arc::new(AtomicI64::new(0));
let volatile_calls_udf = Arc::clone(&volatile_calls);
let volatile_udf = create_udf(
"volatile_tick",
vec![DataType::Int64],
DataType::Int64,
Volatility::Volatile,
Arc::new(move |_| {
let next = volatile_calls_udf.fetch_add(1, Ordering::SeqCst) + 1;
Ok(ColumnarValue::Scalar(ScalarValue::Int64(Some(next))))
}),
);
let volatile_arg = create_physical_expr(
&volatile_udf.call(vec![col("value")]),
&df_schema,
&ExecutionProps::new(),
&PhysicalPlanningContext::default(),
)
.unwrap();
let immutable_calls = Arc::new(AtomicI64::new(0));
let immutable_calls_udf = Arc::clone(&immutable_calls);
let immutable_udf = create_udf(
"immutable_tick",
vec![DataType::Int64],
DataType::Int64,
Volatility::Immutable,
Arc::new(move |_| {
let next = immutable_calls_udf.fetch_add(1, Ordering::SeqCst) + 1;
Ok(ColumnarValue::Scalar(ScalarValue::Int64(Some(next))))
}),
);
let immutable_arg = create_physical_expr(
&immutable_udf.call(vec![col("value")]),
&df_schema,
&ExecutionProps::new(),
&PhysicalPlanningContext::default(),
)
.unwrap();
let make_program =
|id: usize, alias: &str, arg: Arc<dyn PhysicalExpr>, col_idx: usize| {
let count = count_udaf();
let expression = Arc::new(
AggregateExprBuilder::new(Arc::clone(&count), vec![arg])
.schema(Arc::clone(&schema))
.alias(alias)
.build()
.unwrap(),
);
let function = AggregateFunction {
func: count,
params: AggregateFunctionParams {
args: vec![],
distinct: false,
filter: None,
order_by: vec![],
null_treatment: None,
},
};
AggregateProgram::try_new(
AggregateId::try_new(id, 2).unwrap(),
expression,
function,
ManagedAggregateBackend::Accumulator,
AccumulatorInputMode::Batch,
false,
ResolvedInputColumn::new_validated(col_idx),
None,
schema.as_ref(),
)
.unwrap()
};
let programs = vec![
make_program(0, "agg_volatile", volatile_arg, 1),
make_program(1, "agg_immutable", immutable_arg, 2),
];
assert!(programs[0].has_volatile_inputs());
assert!(!programs[1].has_volatile_inputs());
let argument_memory =
crate::execution::common::memory::new_unbounded_state_memory().new_empty();
let mut arguments = vec![Vec::new(), Vec::new()];
let mut cached_batch = None;
let mut provider = ValueProvider::Row {
arguments: &mut arguments,
argument_memory: &argument_memory,
programs: &programs,
cached_batch: &mut cached_batch,
input: &input,
location: (0, 0),
symbol_id: None,
symbol_name_arrays: &[],
};
let mut work = CoarseWorkCounter::new();
let volatile_id = AggregateId::try_new(0, 2).unwrap();
let immutable_id = AggregateId::try_new(1, 2).unwrap();
let first = provider
.evaluate_args(volatile_id, &mut work, &mut |_| Ok(()))
.unwrap()[0]
.as_any()
.downcast_ref::<Int64Array>()
.unwrap()
.value(0);
let first_bytes = argument_memory.size();
let second = provider
.evaluate_args(volatile_id, &mut work, &mut |_| Ok(()))
.unwrap()[0]
.as_any()
.downcast_ref::<Int64Array>()
.unwrap()
.value(0);
assert_eq!(argument_memory.size(), first_bytes);
assert_eq!((first, second), (1, 2));
assert_eq!(volatile_calls.load(Ordering::SeqCst), 2);
let cached_first = provider
.evaluate_args(immutable_id, &mut work, &mut |_| Ok(()))
.unwrap()[0]
.as_any()
.downcast_ref::<Int64Array>()
.unwrap()
.value(0);
let cached_second = provider
.evaluate_args(immutable_id, &mut work, &mut |_| Ok(()))
.unwrap()[0]
.as_any()
.downcast_ref::<Int64Array>()
.unwrap()
.value(0);
assert_eq!((cached_first, cached_second), (1, 1));
assert_eq!(immutable_calls.load(Ordering::SeqCst), 1);
}
#[test]
fn direct_classifier_arg_rejects_missing_symbol_or_name_array() {
use crate::core::{MatchMetadataColumn, SymbolId};
let argument_memory =
crate::execution::common::memory::new_unbounded_state_memory().new_empty();
let schema = Arc::new(Schema::new(vec![Field::new(
MatchMetadataColumn::Classifier.as_ref(),
DataType::Utf8,
true,
)]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![Arc::new(StringArray::from(vec![None::<&str>])) as ArrayRef],
)
.unwrap();
let input = BatchCollection::try_new(vec![batch], schema).unwrap();
let classifier_expr: Arc<dyn PhysicalExpr> =
Arc::new(Column::new(MatchMetadataColumn::Classifier.as_ref(), 0));
let missing_symbol = try_evaluate_direct_arg(
&classifier_expr,
None,
&input,
(0, 0),
None,
&[],
&argument_memory,
)
.unwrap()
.unwrap_err();
assert!(
missing_symbol
.to_string()
.contains("without an active symbol"),
"{missing_symbol}"
);
let sym_a = SymbolId::try_new(1, 2).unwrap();
let missing_array = try_evaluate_direct_arg(
&classifier_expr,
None,
&input,
(0, 0),
Some(sym_a),
&[None, None],
&argument_memory,
)
.unwrap()
.unwrap_err();
assert!(
missing_array.to_string().contains("no bound name array"),
"{missing_array}"
);
}
}