use crate::execution::storage::PendingOutput;
use std::borrow::{Borrow, BorrowMut};
use std::sync::Arc;
use crate::core::{
AggregateId, MatchMetadataColumn, MatchRecognizeOutputSpec, NormalizedPattern,
RowsPerMatch, SymbolId, managed_aggregate_col_name,
};
use crate::planning::{AccumulatorInputMode, ManagedAggregateBackend};
use datafusion::arrow::datatypes::{Field, Schema, SchemaRef};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::{Result, ScalarValue};
use datafusion::logical_expr::expr::{AggregateFunction, AggregateFunctionParams};
use datafusion::physical_expr::PhysicalExpr;
use datafusion::physical_expr::aggregate::AggregateExprBuilder;
use datafusion::physical_plan::expressions::{Column, Literal};
use datafusion::physical_plan::metrics::ExecutionPlanMetricsSet;
use crate::config::{MatchRecognizeConfig, YieldPolicy};
use crate::execution::common::progress::ComputeStep;
use crate::execution::identity::{CollectionHeadGeneration, MatchPartitionId};
use crate::execution::matching::program::contracts::ExecutableMatchProgramInput;
use crate::execution::matching::row_loop::state::LogicalPartitionBinding;
use crate::execution::matching::{
AggregateProgram, PatternMatcher, ProcessRowsInput, ResolvedInputColumn,
RowOutputHarness, ScanContext, build_test_executable,
};
use crate::execution::metrics::PatternMetrics;
use crate::execution::storage::accumulator::MatchAccumulator;
use crate::execution::storage::collection::BatchCollection;
use crate::execution::storage::history_buffer::SharedHistoryBuffer;
use crate::nfa::CompiledAutomaton;
const TEST_COLLECTION_HEAD_GENERATION: CollectionHeadGeneration =
CollectionHeadGeneration::new(1);
pub(crate) use crate::execution::matching::static_test_support::{
CountingBoolExpr, TEST_OUTPUT_METADATA,
};
pub(crate) fn build_test_matcher(
input_schema: SchemaRef,
normalized_pattern: NormalizedPattern,
automaton: Arc<CompiledAutomaton>,
config: &MatchRecognizeConfig,
configure: impl FnOnce(&mut ExecutableMatchProgramInput),
) -> Result<PatternMatcher> {
let executable =
build_test_executable(input_schema, normalized_pattern, automaton, configure)?;
Ok(PatternMatcher::from_executable(&executable, config))
}
pub(crate) fn add_count_accumulator(
batch: RecordBatch,
symbol_id: SymbolId,
) -> (RecordBatch, AggregateProgram, String) {
add_managed_aggregate(
batch,
datafusion::functions_aggregate::count::count_udaf(),
Arc::new(Literal::new(ScalarValue::Int64(Some(1)))),
Some(symbol_id),
ManagedAggregateBackend::Accumulator,
AggregateId::try_new(0, 1).unwrap(),
true,
)
}
pub(crate) fn add_count_register(
batch: RecordBatch,
symbol_id: SymbolId,
) -> (RecordBatch, AggregateProgram, String) {
add_count_register_at(batch, Some(symbol_id), 0, 1)
}
pub(crate) fn add_count_register_at(
batch: RecordBatch,
symbol_id: Option<SymbolId>,
aggregate_index: usize,
aggregate_count: usize,
) -> (RecordBatch, AggregateProgram, String) {
add_managed_aggregate(
batch,
datafusion::functions_aggregate::count::count_udaf(),
Arc::new(Literal::new(ScalarValue::Int64(Some(1)))),
symbol_id,
ManagedAggregateBackend::Registers,
AggregateId::try_new(aggregate_index, aggregate_count).unwrap(),
true,
)
}
pub(crate) fn add_nav_register_at(
batch: RecordBatch,
input_column: &str,
udaf: Arc<datafusion::logical_expr::AggregateUDF>,
symbol_id: Option<SymbolId>,
aggregate_index: usize,
aggregate_count: usize,
) -> (RecordBatch, AggregateProgram, String) {
let input_idx = batch
.schema()
.index_of(input_column)
.expect("managed navigation input column should exist");
add_managed_aggregate(
batch,
udaf,
Arc::new(Column::new(input_column, input_idx)),
symbol_id,
ManagedAggregateBackend::Registers,
AggregateId::try_new(aggregate_index, aggregate_count).unwrap(),
false,
)
}
fn add_managed_aggregate(
batch: RecordBatch,
udaf: Arc<datafusion::logical_expr::AggregateUDF>,
input: Arc<dyn PhysicalExpr>,
symbol_id: Option<SymbolId>,
backend: ManagedAggregateBackend,
aggregate_id: AggregateId,
counts_every_row: bool,
) -> (RecordBatch, AggregateProgram, String) {
let function = AggregateFunction {
func: Arc::clone(&udaf),
params: AggregateFunctionParams {
args: vec![],
distinct: false,
filter: None,
order_by: vec![],
null_treatment: None,
},
};
let column_name = managed_aggregate_col_name(aggregate_id.index());
let expression = Arc::new(
AggregateExprBuilder::new(udaf, vec![input])
.schema(batch.schema())
.alias(&column_name)
.build()
.expect("managed aggregate expression should build"),
);
let data_type = expression.field().data_type().clone();
let mut fields = batch.schema().fields().to_vec();
fields.push(Arc::new(Field::new(&column_name, data_type.clone(), true)));
let schema = Arc::new(Schema::new(fields));
let mut columns = batch.columns().to_vec();
columns.push(
ScalarValue::try_from(&data_type)
.expect("managed aggregate null placeholder should build")
.to_array_of_size(batch.num_rows())
.expect("managed aggregate placeholder array should build"),
);
let batch = RecordBatch::try_new(Arc::clone(&schema), columns)
.expect("managed aggregate test batch should build");
let program = AggregateProgram::try_new(
aggregate_id,
expression,
function,
backend,
AccumulatorInputMode::Batch,
counts_every_row,
ResolvedInputColumn::new_validated(schema.fields().len() - 1),
symbol_id,
schema.as_ref(),
)
.expect("managed aggregate test program should build");
(batch, program, column_name)
}
pub(crate) fn test_output_program(
batch: &RecordBatch,
automaton: &CompiledAutomaton,
metadata: Vec<MatchMetadataColumn>,
rows_per_match: RowsPerMatch,
) -> RowOutputHarness {
let (classifier_bitset_symbol_ids, classifier_bitset_symbols): (Vec<_>, Vec<_>) =
automaton
.symbols_iter()
.map(|(symbol_id, name)| (symbol_id, name.to_string()))
.unzip();
let spec = MatchRecognizeOutputSpec::new(
(0..batch.num_columns()).collect(),
metadata,
classifier_bitset_symbols,
);
RowOutputHarness::new(spec, classifier_bitset_symbol_ids.into(), rows_per_match)
}
pub(crate) struct CollectionTestDriver<M = PatternMatcher> {
pub(crate) matcher: M,
pub(crate) accumulator: MatchAccumulator,
pub(crate) collection: BatchCollection,
pub(crate) bool_columns:
Arc<crate::execution::matching::symbol_columns::MultiBatchBoolColumnsBacking>,
pub(crate) metrics: PatternMetrics,
pub(crate) pending_output: PendingOutput,
pub(crate) scratch: Option<ScanContext>,
pub(crate) partition_id: MatchPartitionId,
pub(crate) head_generation: CollectionHeadGeneration,
pub(crate) start_row: usize,
pub(crate) end_row: usize,
pub(crate) candidate_end_row: Option<usize>,
pub(crate) final_flush: bool,
pub(crate) global_offset: usize,
}
impl CollectionTestDriver {
pub(crate) fn try_new(
batch: RecordBatch,
normalized_pattern: NormalizedPattern,
automaton: Arc<CompiledAutomaton>,
config: &MatchRecognizeConfig,
flush_threshold: usize,
output: RowOutputHarness,
configure: impl FnOnce(&mut ExecutableMatchProgramInput),
) -> Result<Self> {
let matcher = build_test_matcher(
batch.schema(),
normalized_pattern,
automaton,
config,
configure,
)?;
Self::try_new_with_matcher(batch, flush_threshold, output, matcher)
}
}
impl<M: Borrow<PatternMatcher> + BorrowMut<PatternMatcher>> CollectionTestDriver<M> {
pub(crate) fn try_new_with_matcher(
batch: RecordBatch,
flush_threshold: usize,
output: RowOutputHarness,
matcher: M,
) -> Result<Self> {
let schema = batch.schema();
let compiled = matcher.borrow().automaton_arc();
let accumulator = MatchAccumulator::try_new_unbounded(
Arc::clone(&compiled),
flush_threshold,
output.try_build(schema.as_ref(), compiled.as_ref())?,
)?;
let collection = BatchCollection::try_new(vec![batch], schema)?;
let bool_columns = matcher
.borrow()
.physical_bool_columns_for_test(&collection)?;
let mut scratch = ScanContext::try_new(
compiled.nfa().state_count(),
compiled.id_to_symbol().len(),
1,
)?;
scratch.partition.execution = Some(matcher.borrow().execution_binding());
scratch.partition.logical = Some(LogicalPartitionBinding {
partition_id: MatchPartitionId::new(0),
key: crate::execution::matching::shared_empty_partition_key().into(),
});
Ok(Self {
matcher,
accumulator,
end_row: collection.num_rows(),
collection,
bool_columns,
metrics: PatternMetrics::new_stateful(&ExecutionPlanMetricsSet::new(), 0),
pending_output: PendingOutput::default(),
scratch: Some(scratch),
partition_id: MatchPartitionId::new(0),
head_generation: TEST_COLLECTION_HEAD_GENERATION,
start_row: 0,
candidate_end_row: None,
final_flush: true,
global_offset: 0,
})
}
pub(crate) fn enable_matcher_metrics(&mut self) {
self.matcher.borrow_mut().services.metrics = Some(Box::new(self.metrics.clone()));
}
pub(crate) fn replace_collection(
&mut self,
collection: BatchCollection,
) -> Result<()> {
let bool_columns = self
.matcher
.borrow()
.physical_bool_columns_for_test(&collection)?;
self.collection = collection;
self.bool_columns = bool_columns;
Ok(())
}
pub(crate) fn configure_initial_partition_key(
&mut self,
supplied: Option<crate::execution::matching::PartitionKey>,
) -> Result<()> {
let scan = self
.scratch
.as_mut()
.expect("test driver owns scratch state");
scan.collection
.validate_not_poisoned("initial partition configuration")?;
scan.validate_collection_start(self.partition_id)?;
let key = match supplied.as_ref() {
Some(key) if !key.is_empty() => Arc::clone(key),
Some(_) | None => crate::execution::matching::shared_empty_partition_key(),
};
scan.partition
.logical
.as_mut()
.expect("initial partition is bound")
.key = key.into();
Ok(())
}
pub(crate) fn step(
&mut self,
yield_policy: YieldPolicy,
history_buffer: Option<&SharedHistoryBuffer>,
) -> Result<ComputeStep> {
let matcher = self.matcher.borrow_mut();
let scratch = self.scratch.as_mut().expect("driver owns the partition");
matcher
.process_rows_collection(
scratch,
ProcessRowsInput {
stop_on_output: false,
batches: &self.collection,
bool_columns: &self.bool_columns,
start_row: self.start_row,
end_row: self.end_row,
candidate_end_row: self.candidate_end_row,
out: &mut self.accumulator,
pending_output: &mut self.pending_output,
history_buffer,
metrics: &self.metrics,
yield_policy,
partition_id: self.partition_id,
head_generation: self.head_generation,
final_flush: self.final_flush,
global_offset: self.global_offset,
skip_direct: crate::execution::matching::SkipDirect::None,
batched_base_routes: None,
},
)
.map(|(step, _)| step)
}
pub(crate) fn assert_bound_head(&self) {
let collection = &self
.scratch
.as_ref()
.expect("driver owns the partition")
.collection;
assert_eq!(collection.bound_partition_id(), Some(self.partition_id));
assert_eq!(collection.head_generation(), Some(self.head_generation));
}
pub(crate) fn flush_output(
&mut self,
max_processed_row: usize,
final_flush: bool,
history_buffer: Option<&SharedHistoryBuffer>,
) -> Result<()> {
self.accumulator.max_processed_row = max_processed_row;
if let Some(batch) = self.accumulator.flush_collection(
&self.collection,
self.global_offset,
history_buffer,
final_flush,
)? {
self.pending_output.push_back(batch)?;
}
Ok(())
}
pub(crate) fn concat_output(&self) -> RecordBatch {
let batches = self.pending_output.iter().cloned().collect::<Vec<_>>();
assert!(!batches.is_empty(), "test driver produced no output");
datafusion::arrow::compute::concat_batches(&batches[0].schema(), &batches)
.expect("test driver output batches should concatenate")
}
}