use super::*;
use crate::config::{CancellationPolicy, MatchRecognizeConfig};
use crate::core::{
EmptyMatchesMode, MatchMetadataColumn, MatchRecognizeOutputSpec, NormalizedPattern,
Pattern, RepetitionQuantifier, RowsPerMatch, Symbol, SymbolId,
};
use crate::execution::identity::{
CollectionHeadGeneration, ExecutionPartitionId, MatchPartitionId,
};
use crate::execution::matching::row_loop::state::{
ActiveContainerGeneration, ScanContext,
};
use crate::execution::matching::{
ExecutableOutputPlan, PartitionKey, PartitionKeyRows, owned_partition_key,
shared_empty_partition_key,
};
use crate::execution::storage::buffer::{HeadPartitions, PartitionedBuffer};
use crate::nfa::CompiledAutomaton;
use datafusion::arrow::array::{ArrayRef, BooleanArray, UInt32Array};
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::common::ScalarValue;
use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryConsumer, MemoryPool};
use std::ops::Range;
use std::sync::atomic::AtomicBool;
fn make_test_schema() -> SchemaRef {
Arc::new(Schema::new(vec![
Field::new("id", DataType::UInt32, false),
Field::new("__mr_symbol_a", DataType::Boolean, false),
]))
}
fn test_normalized_pattern() -> NormalizedPattern {
NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named("A".into())))
}
fn create_test_pattern() -> Arc<CompiledAutomaton> {
let pattern = test_normalized_pattern();
Arc::new(CompiledAutomaton::compile(&pattern, &["A".into()]).unwrap())
}
fn create_test_matcher(
schema: &SchemaRef,
compiled: Arc<CompiledAutomaton>,
) -> PatternMatcher {
create_test_matcher_with_rows(
schema,
test_normalized_pattern(),
compiled,
RowsPerMatch::OneRow,
)
}
impl PartitionScan {
fn prepare_partitions(
&mut self,
metadata_reservation: &MemoryReservation,
ranges: &[Range<usize>],
partition_columns: &[ArrayRef],
end: PhysicalHeadEnd,
collection: &BatchCollection,
matcher: &PatternMatcher,
) -> Result<PreparedPartitions> {
let key_rows = test_case_key_rows(partition_columns, metadata_reservation)?;
metadata_reservation.try_grow(size_of_val(ranges))?;
let continues_tail = if let Some(key) = self.open_tail_key()? {
if let Some(first) = key_rows.first() {
key.same_values(&*first.key(0)?)?
} else {
collection.num_rows() != 0 && key.is_empty()
}
} else {
false
};
let mut preparation = self.begin_partition_preparation(
HeadPartitions {
ranges: ranges.to_vec(),
open_key: open_key_case(&key_rows, ranges, end, continues_tail)?,
end,
continues_tail,
},
collection.num_rows(),
matcher,
metadata_reservation,
)?;
let mut governor = WorkGovernor::default();
while !preparation.advance(
collection,
matcher,
&mut governor,
self.yield_policy,
)? {}
self.finish_preparation(preparation)
}
}
fn open_key_case(
rows: &[PartitionKeyRows],
ranges: &[Range<usize>],
end: PhysicalHeadEnd,
continues_tail: bool,
) -> Result<Option<PartitionKeyRows>> {
if !end.ends_partition()
&& !(continues_tail && ranges.len() == 1)
&& let (Some(batch), Some(range)) = (rows.first(), ranges.last())
&& range.start < batch.rows
{
return batch.slice(range.start, 1).map(Some);
}
Ok(None)
}
fn head_segments(
prepared: &PreparedPartitions,
) -> impl Iterator<Item = HeadSegment> + '_ {
let mut cursor = prepared.cursor;
std::iter::from_fn(move || cursor.next_segment(&prepared.head))
}
fn test_case_key_rows(
columns: &[ArrayRef],
memory: &MemoryReservation,
) -> Result<Vec<PartitionKeyRows>> {
if columns.is_empty() {
return Ok(Vec::new());
}
let batch = RecordBatch::try_from_iter(
columns
.iter()
.enumerate()
.map(|(index, column)| (format!("key{index}"), Arc::clone(column))),
)?;
let key_memory = memory.new_empty();
key_memory.try_grow(
datafusion::common::utils::memory::RecordBatchMemoryCounter::new()
.count_batch_with_array_overhead(&batch),
)?;
Ok(vec![PartitionKeyRows::full(
crate::execution::matching::PartitionKeyBatch::new(batch, key_memory),
)])
}
fn discover_partitions(
context: &mut PartitionScan,
ranges: &[Range<usize>],
columns: &[ArrayRef],
rows: usize,
end: PhysicalHeadEnd,
) -> Result<Vec<PartitionDescriptor>> {
let memory = crate::execution::common::memory::new_unbounded_state_memory();
let collection = preparation_collection(rows);
let matcher = create_test_matcher(collection.schema(), create_test_pattern());
let prepared = context.prepare_partitions(
&memory,
ranges,
columns,
end,
&collection,
&matcher,
)?;
head_segments(&prepared)
.map(|segment| prepared.descriptor(&segment, context))
.collect()
}
fn preparation_collection(rows: usize) -> BatchCollection {
let schema = make_test_schema();
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(UInt32Array::from_iter_values(0..rows as u32)),
Arc::new(BooleanArray::from(vec![true; rows])),
],
)
.unwrap();
BatchCollection::try_new(vec![batch], schema).unwrap()
}
fn create_test_matcher_with_rows(
schema: &SchemaRef,
normalized_pattern: NormalizedPattern,
compiled: Arc<CompiledAutomaton>,
rows_per_match: RowsPerMatch,
) -> PatternMatcher {
crate::execution::matching::build_test_matcher(
Arc::clone(schema),
normalized_pattern,
compiled,
&MatchRecognizeConfig::default(),
|input| input.set_rows_per_match(rows_per_match),
)
.expect("test matcher should build")
}
fn resolve_test_output(
input_schema: &SchemaRef,
compiled: &CompiledAutomaton,
rows_per_match: RowsPerMatch,
) -> Arc<ExecutableOutputPlan> {
let passthrough_indices = (0..input_schema.fields().len()).collect();
let meta_cols = MatchMetadataColumn::public_output().to_vec();
let output_spec =
MatchRecognizeOutputSpec::new(passthrough_indices, meta_cols, vec!["A".into()]);
ExecutableOutputPlan::try_rows(
input_schema.as_ref(),
output_spec,
Arc::from([SymbolId::try_new(1, compiled.num_symbols())
.expect("single-symbol output test_case has runtime symbol A")]),
rows_per_match,
compiled,
)
.expect("test output program should resolve")
}
fn create_test_context() -> PartitionScan {
let schema = make_test_schema();
let compiled = create_test_pattern();
let resolved_output =
resolve_test_output(&schema, compiled.as_ref(), RowsPerMatch::OneRow);
PartitionScan::try_new_for_test(schema, resolved_output, 1000, 100, compiled, 1)
.expect("test context should build")
}
fn scan_context(compiled: &CompiledAutomaton, next_match: u64) -> ScanContext {
ScanContext::new(
compiled.nfa().state_count(),
compiled.id_to_symbol().len(),
next_match,
)
}
fn partition_key_arc(scratch: &ScanContext) -> &PartitionKey {
scratch
.partition
.logical()
.expect("test scan context should retain its canonical partition-key Arc")
.key
.canonical()
.unwrap()
}
type SchedulerOwnerFact = (
Option<MatchPartitionId>,
Option<MatchPartitionId>,
Option<Vec<ScalarValue>>,
);
#[derive(Debug, PartialEq, Eq)]
struct SchedulerFact {
issued: usize,
current: Option<SchedulerOwnerFact>,
reusable: Option<SchedulerOwnerFact>,
}
fn scheduler_owner_fact(context: &ScanContext) -> SchedulerOwnerFact {
let logical = context.partition.logical.as_ref();
(
logical.map(|binding| binding.partition_id),
context.collection.bound_partition_id(),
logical
.and_then(|binding| binding.key.canonical())
.map(|key| key.scalar_values().unwrap()),
)
}
fn scheduler_fact(ctx: &PartitionScan) -> SchedulerFact {
SchedulerFact {
issued: ctx.next_partition_id,
current: ctx.current_scan().map(scheduler_owner_fact),
reusable: ctx
.scratch
.as_deref()
.filter(|scan| scan.partition.logical.is_none())
.map(scheduler_owner_fact),
}
}
#[test]
fn yielded_runtime_compilation_resumes_through_scheduler_before_binding() -> Result<()> {
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::UInt32, false),
Field::new("__mr_symbol_a", DataType::Boolean, false),
Field::new("__mr_symbol_b", DataType::Boolean, false),
]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(UInt32Array::from(vec![0])),
Arc::new(BooleanArray::from(vec![true])),
Arc::new(BooleanArray::from(vec![false])),
],
)?;
let collection = BatchCollection::try_new(vec![batch], Arc::clone(&schema))?;
let pattern = NormalizedPattern::Ast(Pattern::Alternation(vec![
Pattern::Repetition(
Box::new(Pattern::Symbol(Symbol::Named("A".into()))),
RepetitionQuantifier::Range(1, 8_192),
),
Pattern::Symbol(Symbol::Named("B".into())),
]));
let compiled = Arc::new(CompiledAutomaton::compile(
&pattern,
&["A".into(), "B".into()],
)?);
let absent = compiled
.symbols_iter()
.find_map(|(id, name)| (name == "B").then_some(id))
.expect("test pattern has symbol B");
let output = ExecutableOutputPlan::try_rows(
schema.as_ref(),
MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
Arc::from([]),
RowsPerMatch::OneRow,
compiled.as_ref(),
)?;
let mut context = PartitionScan::try_new_for_test(
Arc::clone(&schema),
output,
128,
1,
Arc::clone(&compiled),
1,
)?;
let mut matcher = create_test_matcher_with_rows(
&schema,
pattern,
Arc::clone(&compiled),
RowsPerMatch::OneRow,
);
let memory = crate::execution::common::memory::new_unbounded_state_memory();
let partitions = context.prepare_partitions(
&memory,
std::slice::from_ref(&(0..1)),
&[],
PhysicalHeadEnd::InputEnd,
&collection,
&matcher,
)?;
let metrics = PatternMetrics::new_stateful(
&datafusion::physical_plan::metrics::ExecutionPlanMetricsSet::new(),
0,
);
let mut pending_output = PendingOutput::default();
let mut bound = BoundHead {
stop_on_output: false,
scan: &mut context,
partitions,
collection: &collection,
origin: 0,
};
let drive = |bound: &mut BoundHead<'_>,
matcher: &mut PatternMatcher,
pending_output: &mut PendingOutput| {
bound.advance(ComputeRuntime {
pattern_matcher: matcher,
history_buffer: None,
metrics: &metrics,
pending_output,
})
};
assert_eq!(
drive(&mut bound, &mut matcher, &mut pending_output)?,
ComputeStep::Yield
);
let scan = bound
.scan
.scratch
.as_ref()
.expect("yielded compilation keeps its scheduler owner active");
assert!(scan.collection.is_preparing());
assert!(scan.active_variant.is_none());
assert!(scan.collection.provider_backing().is_none());
let partition_id = scan
.collection
.bound_partition_id()
.expect("pending compilation exposes its logical partition ID");
let issued_after_yield = bound.scan.next_partition_id;
assert!(
matcher
.services
.absent_symbol_cache
.get(&[absent])
.is_none()
);
assert_eq!(bound.origin, 0);
assert!(std::ptr::eq(bound.collection, &collection));
let pending = bound.scan.scratch.as_ref().unwrap();
assert_eq!(pending.partition.global_row_offset, 0);
assert_eq!(pending.partition.partition_start_row, 0);
assert_eq!(pending.partition.partition_end_row, 1);
assert!(pending_output.is_empty());
let mut completed = false;
for _ in 0..256 {
let progress = drive(&mut bound, &mut matcher, &mut pending_output)?;
if progress == ComputeStep::Complete {
completed = true;
break;
}
assert_eq!(progress, ComputeStep::Yield);
if let Some(scan) = bound.scan.scratch.as_ref()
&& scan.collection.is_preparing()
{
assert_eq!(scan.collection.bound_partition_id(), Some(partition_id));
assert!(scan.active_variant.is_none());
assert!(scan.collection.provider_backing().is_none());
}
}
drop(bound);
assert!(
completed,
"runtime compilation and its one-row match must complete"
);
assert_eq!(
context.next_partition_id, issued_after_yield,
"compiler resumes must not issue another collection continuation"
);
let cached = matcher
.services
.absent_symbol_cache
.get(&[absent])
.expect("completed compilation publishes its cache variant");
let recycled = context
.scratch
.as_deref()
.filter(|scan| scan.partition.logical.is_none())
.expect("the completed partition returns its scan context");
assert!(Arc::ptr_eq(
recycled
.active_variant
.as_ref()
.unwrap()
.resolve(matcher.program.base_variant()),
&cached
));
assert_eq!(metrics.matches_emitted.value(), 1);
assert_eq!(pending_output.len(), 1);
assert_eq!(pending_output.pop_front().unwrap().num_rows(), 1);
Ok(())
}
#[test]
fn collection_head_generation_exhaustion_is_atomic() {
let mut context = create_test_context();
let memory = crate::execution::common::memory::new_unbounded_state_memory();
let before = scheduler_fact(&context);
let collection = preparation_collection(0);
let matcher = create_test_matcher(collection.schema(), create_test_pattern());
for generation in [u64::MAX, u64::MAX - 1] {
context.next_head_generation = CollectionHeadGeneration::new(generation);
let prepared = context.prepare_partitions(
&memory,
&[],
&[],
PhysicalHeadEnd::InputEnd,
&collection,
&matcher,
);
if generation == u64::MAX {
let Err(DataFusionError::ResourcesExhausted(message)) = prepared else {
panic!("exhausted generation must fail before publication")
};
assert!(message.contains("collection head generation space exhausted"));
} else {
assert_eq!(
prepared.unwrap().generation,
CollectionHeadGeneration::new(generation)
);
}
assert_eq!(
context.next_head_generation,
CollectionHeadGeneration::new(u64::MAX)
);
assert_eq!(scheduler_fact(&context), before);
}
}
#[test]
fn partition_preparation_chunks_keep_ids_private_and_release_discovery_columns() {
for (rows, width, continues_tail) in
[(257, 1, false), (1, 257, false), (1, 257, true)]
{
let mut test_case = PartitionActivationHarness::new();
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::UInt32, false),
Field::new("__mr_symbol_a", DataType::Boolean, false),
Field::new("__mr_symbol_b", DataType::Boolean, false),
]));
let pattern = NormalizedPattern::Ast(Pattern::Alternation(vec![
Pattern::Symbol(Symbol::Named("A".into())),
Pattern::Symbol(Symbol::Named("B".into())),
]));
let compiled = Arc::new(
CompiledAutomaton::compile(&pattern, &["A".into(), "B".into()]).unwrap(),
);
test_case.matcher = create_test_matcher_with_rows(
&schema,
pattern,
compiled,
RowsPerMatch::OneRow,
);
test_case.ctx.has_partition_by = true;
test_case.ctx.yield_policy = crate::config::YieldPolicy::from_test_budget(1);
let owner_key = if continues_tail {
test_case
.activate(
&vec![ScalarValue::UInt32(Some(0)); width],
0..1,
0,
true,
CollectionHeadGeneration::new(1),
)
.unwrap();
Some(Arc::clone(partition_key_arc(test_case.current())))
} else {
None
};
let context = &mut test_case.ctx;
let matcher = &test_case.matcher;
let mut governor = WorkGovernor::default();
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(usize::MAX));
let memory = MemoryConsumer::new("partition-preparation-test").register(&pool);
let column = Arc::new(UInt32Array::from_iter_values(0..rows as u32)) as ArrayRef;
let column_owner = Arc::downgrade(&column);
let columns = vec![column; width];
let ranges: Vec<_> = (0..rows).map(|row| row..row + 1).collect();
let generation = context.next_head_generation;
let scheduler_before = scheduler_fact(context);
let key_rows = test_case_key_rows(&columns, &memory).unwrap();
let key_batch = Arc::downgrade(&key_rows[0].batch);
drop(columns);
let head_bytes = ranges.capacity() * size_of::<Range<usize>>();
memory.try_grow(head_bytes).unwrap();
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(UInt32Array::from_iter_values(0..rows as u32)),
Arc::new(BooleanArray::from(vec![true; rows])),
Arc::new(BooleanArray::from(vec![false; rows])),
],
)
.unwrap();
let collection = BatchCollection::try_new(vec![batch], schema).unwrap();
let open_key = open_key_case(
&key_rows,
&ranges,
PhysicalHeadEnd::OpenTail,
continues_tail,
)
.unwrap();
drop(key_rows);
let before = pool.reserved();
let mut preparation = context
.begin_partition_preparation(
HeadPartitions {
ranges,
continues_tail,
open_key,
end: PhysicalHeadEnd::OpenTail,
},
rows,
matcher,
&memory,
)
.unwrap();
assert!(head_bytes > 0);
assert_eq!(memory.size(), head_bytes);
let mut yielded = 0;
let prepared = loop {
let epoch = governor.progress_epoch_for_observation();
let complete = preparation
.advance(&collection, matcher, &mut governor, context.yield_policy)
.unwrap();
let completed = governor.progress_epoch_for_observation() - epoch;
assert_eq!(scheduler_fact(context), scheduler_before);
assert_eq!(memory.size(), head_bytes);
assert!(pool.reserved() > before);
if complete {
break context.finish_preparation(preparation).unwrap();
}
assert!(completed > 0, "a suspended preparation must make progress");
assert_eq!(context.next_head_generation, generation);
yielded += 1;
assert!(yielded < 32, "descriptor preparation did not complete");
};
assert!(
yielded > 0,
"preparing two physical Boolean columns must exercise a real suspension"
);
assert_eq!(prepared.generation, generation);
assert_eq!(context.next_head_generation.get(), generation.get() + 1);
assert_eq!(column_owner.upgrade().is_some(), !continues_tail);
assert_eq!(key_batch.strong_count(), usize::from(!continues_tail));
assert_eq!(head_segments(&prepared).count(), rows);
for (row, segment) in head_segments(&prepared).enumerate() {
let descriptor = prepared.descriptor(&segment, context).unwrap();
assert_eq!(&descriptor.range, &(row..row + 1));
assert_eq!(descriptor.partition_id, MatchPartitionId::new(row));
assert_eq!(descriptor.ends_partition, row + 1 < rows);
if descriptor.ends_partition {
assert!(descriptor.key.canonical().is_none());
} else {
assert_eq!(
descriptor.key.canonical().unwrap().scalar_values().unwrap(),
vec![ScalarValue::UInt32(Some(row as u32)); width]
);
}
if let Some(owner_key) = &owner_key {
assert!(Arc::ptr_eq(descriptor.key.canonical().unwrap(), owner_key));
}
}
drop(prepared);
assert!(column_owner.upgrade().is_none());
assert_eq!(pool.reserved(), head_bytes);
drop(memory);
assert_eq!(pool.reserved(), 0);
}
}
#[tokio::test]
async fn replay_suspends_before_a_late_key_mismatch_and_closes_the_old_tail() -> Result<()>
{
let mut test_case = PartitionActivationHarness::new();
test_case.ctx.has_partition_by = true;
test_case.ctx.yield_policy = crate::config::YieldPolicy::from_test_budget(1);
let key = vec![ScalarValue::UInt32(Some(0)); 257];
test_case.activate(&key, 0..1, 0, true, CollectionHeadGeneration::new(1))?;
let mut columns = vec![Arc::new(UInt32Array::from(vec![0])) as ArrayRef; 257];
columns[256] = Arc::new(UInt32Array::from(vec![1]));
let memory =
crate::execution::common::memory::new_unbounded_state_memory().new_empty();
let key_rows = test_case_key_rows(&columns, &memory)?;
memory.try_grow(key_rows.capacity() * size_of::<PartitionKeyRows>())?;
let mut governor = WorkGovernor::default();
let slice = crate::execution::common::scheduling::SliceControl::for_test_budget(
NonZeroUsize::MIN,
);
let open_tail = test_case.ctx.open_tail_key()?;
let (head, memory) = {
let mut replay = Box::pin(PartitionedBuffer::prepare_replay_keys(
preparation_collection(1),
key_rows,
open_tail,
PhysicalHeadEnd::OpenTail,
memory,
&mut governor,
&slice,
|| false,
));
assert!(futures::poll!(&mut replay).is_pending());
replay.await?
};
let (collection, head) = head.into_parts();
let mut preparation = test_case.ctx.begin_partition_preparation(
head,
collection.num_rows(),
&test_case.matcher,
&memory,
)?;
while !preparation.advance(
&collection,
&test_case.matcher,
&mut governor,
test_case.ctx.yield_policy,
)? {}
let prepared = test_case.ctx.finish_preparation(preparation)?;
let descriptors = head_segments(&prepared)
.map(|segment| prepared.descriptor(&segment, &test_case.ctx))
.collect::<Result<Vec<_>>>()?;
assert_eq!(
descriptors
.iter()
.map(|d| (d.partition_id, d.range.clone(), d.ends_partition))
.collect::<Vec<_>>(),
vec![
(MatchPartitionId::new(0), 0..0, true),
(MatchPartitionId::new(1), 0..1, false)
]
);
let mut expected = key;
expected[256] = ScalarValue::UInt32(Some(1));
assert_eq!(
descriptors[1].key.canonical().unwrap().scalar_values()?,
expected
);
Ok(())
}
#[test]
fn only_open_ranges_admit_a_canonical_partition_key() -> Result<()> {
const ROWS: usize = 257;
const LIMIT: usize = 1 << 20;
let collection = preparation_collection(ROWS);
let matcher = create_test_matcher(collection.schema(), create_test_pattern());
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(LIMIT));
let mut context = create_test_context();
context.has_partition_by = true;
for (width, end) in [
(ROWS, PhysicalHeadEnd::OpenTail),
(1, PhysicalHeadEnd::OpenTail),
(1, PhysicalHeadEnd::InputEnd),
] {
let head_memory = MemoryConsumer::new("lazy-partition-keys").register(&pool);
let ranges = (0..ROWS)
.step_by(width)
.map(|start| start..start + width)
.collect::<Vec<_>>();
let column =
UInt32Array::from_iter_values((0..ROWS).map(|row| (row / width) as u32));
let prepared = context.prepare_partitions(
&head_memory,
&ranges,
&[Arc::new(column)],
end,
&collection,
&matcher,
)?;
let retained = pool.reserved();
assert!(retained > 0);
assert_eq!(head_segments(&prepared).count(), ranges.len());
let mut open_descriptors = Vec::new();
for (index, segment) in head_segments(&prepared).enumerate() {
let descriptor = prepared.descriptor(&segment, &context)?;
assert_eq!(descriptor.partition_id, MatchPartitionId::new(index));
assert_eq!(&descriptor.range, &ranges[index]);
if segment.ends_partition {
assert!(descriptor.key.canonical().is_none());
} else {
assert_eq!(
descriptor.key.canonical().unwrap().scalar_values()?,
[ScalarValue::UInt32(Some(index as u32))]
);
open_descriptors.push(descriptor);
}
assert_eq!(pool.reserved(), retained);
}
drop(prepared);
assert!(head_memory.size() > 0);
if open_descriptors.is_empty() {
assert_eq!(pool.reserved(), head_memory.size());
} else {
assert!(pool.reserved() > head_memory.size());
drop(open_descriptors);
assert_eq!(pool.reserved(), head_memory.size());
}
drop(head_memory);
assert_eq!(pool.reserved(), 0);
}
Ok(())
}
#[test]
fn closed_partition_resume_requires_its_head_identity_and_range() -> Result<()> {
let mut test_case = PartitionActivationHarness::new();
test_case.ctx.has_partition_by = true;
let head = test_case.ctx.next_head_generation;
let descriptors = discover_partitions(
&mut test_case.ctx,
&[0..2, 2..3],
&[Arc::new(UInt32Array::from(vec![1, 1, 2]))],
3,
PhysicalHeadEnd::InputEnd,
)?;
let first = &descriptors[0];
let activate = |test_case: &mut PartitionActivationHarness,
descriptor: &PartitionDescriptor,
head_generation| {
test_case.ctx.activate_partition(
descriptor,
0,
head_generation,
&test_case.matcher,
)
};
assert!(first.key.canonical().is_none());
let start = activate(&mut test_case, first, head)?;
test_case.bind_collection(start, head);
let resume = activate(&mut test_case, first, head)?;
assert_eq!(start, resume);
assert_eq!(
test_case.current().collection.bound_partition_id(),
Some(resume)
);
let before = scheduler_fact(&test_case.ctx);
let other_head = CollectionHeadGeneration::new(head.get() + 1);
let mut changed_range = first.clone();
changed_range.range = 0..3;
assert!(activate(&mut test_case, &changed_range, head).is_err());
assert!(activate(&mut test_case, &descriptors[1], head).is_err());
assert!(activate(&mut test_case, first, other_head).is_err());
assert!(test_case.ctx.open_tail_key().is_err());
assert_eq!(scheduler_fact(&test_case.ctx), before);
Ok(())
}
#[test]
fn final_flush_uses_owner_governor_atomically() -> Result<()> {
const ROWS: usize = COARSE_WORK_BATCH_SIZE + 1;
let schema = make_test_schema();
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(UInt32Array::from_iter_values(0..ROWS as u32)) as ArrayRef,
Arc::new(BooleanArray::from(vec![false; ROWS])) as ArrayRef,
],
)?;
let collection = BatchCollection::try_new(vec![batch], Arc::clone(&schema))?;
let normalized_pattern = test_normalized_pattern();
let compiled = Arc::new(CompiledAutomaton::compile(
&normalized_pattern,
&["A".into()],
)?);
let rows_per_match = RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched);
let resolved_output =
resolve_test_output(&schema, compiled.as_ref(), rows_per_match.clone());
let mut context = PartitionScan::try_new_for_test(
Arc::clone(&schema),
resolved_output,
ROWS + 1,
0,
Arc::clone(&compiled),
1,
)?;
context.accumulator.max_processed_row = ROWS;
let abort = Arc::new(AtomicBool::new(true));
let mut matcher = create_test_matcher_with_rows(
&schema,
normalized_pattern,
Arc::clone(&compiled),
rows_per_match,
)
.with_abort_signal(Arc::clone(&abort));
let mut owner = scan_context(compiled.as_ref(), 1);
owner
.scan_state
.governor
.bind_cancellation_policy(CancellationPolicy::try_from_configured(64, 0)?)?;
context.scratch = Some(Box::new(owner));
let memory = crate::execution::common::memory::new_unbounded_state_memory();
let partitions = context.prepare_partitions(
&memory,
&[],
&[],
PhysicalHeadEnd::InputEnd,
&collection,
&matcher,
)?;
let metrics_set = datafusion::physical_plan::metrics::ExecutionPlanMetricsSet::new();
let metrics = PatternMetrics::new_stateful(&metrics_set, 0);
let mut pending_output = PendingOutput::default();
let mut bound = BoundHead {
stop_on_output: false,
scan: &mut context,
partitions,
collection: &collection,
origin: 0,
};
for cancelled in [true, false, false] {
abort.store(cancelled, std::sync::atomic::Ordering::Relaxed);
let result = bound.advance(ComputeRuntime {
pattern_matcher: &mut matcher,
history_buffer: None,
metrics: &metrics,
pending_output: &mut pending_output,
});
if cancelled {
let error = result.unwrap_err();
assert!(error.to_string().contains("cancelled"), "{error}");
assert!(pending_output.is_empty());
assert!(bound.scan.accumulator.is_empty());
assert_eq!(
bound.scan.accumulator.min_unfinalized_presence_row()?,
Some(0)
);
} else {
assert_eq!(result?, ComputeStep::Complete);
assert_eq!(
pending_output.len(),
1,
"retry or repeat flush must publish the row set exactly once"
);
assert_eq!(
pending_output[0].column(0).as_ref(),
&UInt32Array::from_iter_values(0..ROWS as u32)
);
assert_eq!(
bound.scan.accumulator.min_unfinalized_presence_row()?,
Some(ROWS)
);
}
}
Ok(())
}
#[test]
fn summary_batches_yield_without_repeating_matches() -> Result<()> {
use crate::core::MatchSummaryField;
use crate::execution::matching::ExecutableDirectCountSummary;
use datafusion::arrow::array::Int64Array;
const ROWS: usize = 9;
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::Int64, false),
Field::new("__mr_symbol_a", DataType::Boolean, false),
]));
let compiled = create_test_pattern();
let collection = BatchCollection::try_new(
vec![RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int64Array::from_iter_values(0..ROWS as i64)),
Arc::new(BooleanArray::from(vec![true; ROWS])),
],
)?],
Arc::clone(&schema),
)?;
let field = |index, name, nullable| {
MatchSummaryField::new(
index,
Arc::new(Field::new(name, DataType::Int64, nullable)),
)
};
let output = ExecutableOutputPlan::try_direct_counts(
schema.as_ref(),
MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
Arc::from([]),
vec![
ExecutableDirectCountSummary::new(field(0, "n", false), None),
ExecutableDirectCountSummary::new_edge(
field(1, "first_id", true),
None,
0,
false,
),
],
compiled.as_ref(),
)?;
for budget in [0, 1] {
let mut context = PartitionScan::try_new_for_test(
Arc::clone(&schema),
Arc::clone(&output),
4,
budget,
Arc::clone(&compiled),
1,
)?;
let mut matcher = create_test_matcher(&schema, Arc::clone(&compiled));
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(usize::MAX));
let memory = MemoryConsumer::new("final-summary-flush").register(&pool);
let partitions = context.prepare_partitions(
&memory,
std::slice::from_ref(&(0..ROWS)),
&[],
PhysicalHeadEnd::InputEnd,
&collection,
&matcher,
)?;
let other = create_test_context().prepare_partitions(
&memory,
std::slice::from_ref(&(0..ROWS)),
&[],
PhysicalHeadEnd::InputEnd,
&collection,
&matcher,
)?;
let original_other_cursor = other.cursor;
assert_eq!(partitions.generation, other.generation);
assert!(!Arc::ptr_eq(&partitions.bool_columns, &other.bool_columns));
let metrics_set =
datafusion::physical_plan::metrics::ExecutionPlanMetricsSet::new();
let metrics = PatternMetrics::new_stateful(&metrics_set, 0);
let mut pending = PendingOutput::default();
let backing = Arc::downgrade(&partitions.bool_columns);
let mut bound = BoundHead {
stop_on_output: true,
scan: &mut context,
partitions,
collection: &collection,
origin: 0,
};
let mut yielded_batch = false;
let mut checked_head = false;
let mut complete = false;
let mut batches = Vec::new();
for _ in 0..1000 {
let progress = bound.advance(ComputeRuntime {
pattern_matcher: &mut matcher,
history_buffer: None,
metrics: &metrics,
pending_output: &mut pending,
})?;
yielded_batch |= progress == ComputeStep::Yield && !pending.is_empty();
while let Some(batch) = pending.pop_front() {
assert!(batch.num_rows() <= 4);
batches.push(batch);
}
if progress == ComputeStep::Complete {
complete = true;
break;
}
assert!(std::ptr::eq(bound.collection, &collection));
assert_eq!(bound.origin, 0);
assert!(Arc::ptr_eq(
&bound.partitions.bool_columns,
&backing.upgrade().unwrap()
));
assert!(!Arc::ptr_eq(
&bound.partitions.bool_columns,
&other.bool_columns
));
assert_eq!(other.cursor, original_other_cursor);
assert!(other.suspended_partition.is_none());
checked_head = true;
}
assert!(complete, "final flush must make progress");
if budget == 1 {
assert!(
checked_head && yielded_batch,
"between-batch yields must keep the exact selected head"
);
}
assert_eq!(metrics.matches_emitted.value(), ROWS);
assert!(batches.len() >= ROWS.div_ceil(4));
let batch =
datafusion::arrow::compute::concat_batches(&batches[0].schema(), &batches)?;
assert_eq!(batch.num_rows(), ROWS);
assert_eq!(batch.num_columns(), 2);
assert_eq!(batch.column(0).as_ref(), &Int64Array::from(vec![1; ROWS]));
assert_eq!(
batch.column(1).as_ref(),
&Int64Array::from_iter_values(0..ROWS as i64)
);
context.accumulator.validate_no_pending_builder_tail()?;
}
Ok(())
}
#[test]
fn open_tail_discovery_preserves_key_identity_and_closes_at_boundaries() {
let mut test_case = PartitionActivationHarness::new();
test_case.ctx.has_partition_by = true;
test_case.ctx.yield_policy = crate::config::YieldPolicy::from_test_budget(1);
for i in 0..2 {
if i != 0 {
test_case.ctx.finish_partition();
}
test_case
.activate(
&vec![ScalarValue::UInt32(Some(i)); 2],
0..1,
0,
true,
CollectionHeadGeneration::new(1),
)
.unwrap();
}
let ctx = &mut test_case.ctx;
let counters = ctx.next_partition_id;
let tail_id = MatchPartitionId::new(1);
let owner_key = Arc::clone(partition_key_arc(ctx.scratch.as_deref().unwrap()));
let columns = vec![Arc::new(UInt32Array::from(vec![1])) as ArrayRef; 2];
let short_columns = vec![Arc::new(UInt32Array::from(vec![7])) as ArrayRef];
let error = discover_partitions(
ctx,
&[0..1, 1..2],
&short_columns,
2,
PhysicalHeadEnd::OpenTail,
)
.err()
.expect("discovering the open segment must require its key");
assert!(
matches!(&error, DataFusionError::Internal(message)
if message.contains("MATCH_RECOGNIZE open partition has no input representative")),
"{error}"
);
assert_eq!(
ctx.current_scan()
.unwrap()
.partition
.logical()
.unwrap()
.partition_id,
tail_id
);
assert_eq!(ctx.next_partition_id, counters);
assert!(Arc::ptr_eq(
partition_key_arc(ctx.scratch.as_deref().unwrap()),
&owner_key
));
for end in [PhysicalHeadEnd::OpenTail, PhysicalHeadEnd::InputEnd] {
let continued =
discover_partitions(ctx, std::slice::from_ref(&(0..1)), &columns, 1, end)
.unwrap();
assert_eq!(continued.len(), 1);
assert_eq!(continued[0].partition_id, tail_id);
assert_eq!(&continued[0].range, &(0..1));
assert_eq!(continued[0].ends_partition, end.ends_partition());
assert!(Arc::ptr_eq(
continued[0].key.canonical().unwrap(),
&owner_key
));
let mut changed = columns.clone();
changed[1] = Arc::new(UInt32Array::from(vec![5]));
let next =
discover_partitions(ctx, std::slice::from_ref(&(0..1)), &changed, 1, end)
.unwrap();
assert_eq!(next.len(), 2);
assert_eq!(next[0].partition_id, tail_id);
assert_eq!(&next[0].range, &(0..0));
assert!(next[0].ends_partition);
assert!(Arc::ptr_eq(next[0].key.canonical().unwrap(), &owner_key));
assert_eq!(next[1].partition_id, MatchPartitionId::new(2));
assert_eq!(&next[1].range, &(0..1));
assert_eq!(next[1].ends_partition, end.ends_partition());
}
let final_descriptors =
discover_partitions(ctx, &[], &[], 0, PhysicalHeadEnd::InputEnd).unwrap();
assert_eq!(final_descriptors.len(), 1);
assert_eq!(final_descriptors[0].partition_id, tail_id);
assert_eq!(&final_descriptors[0].range, &(0..0));
assert!(final_descriptors[0].ends_partition);
assert!(Arc::ptr_eq(
final_descriptors[0].key.canonical().unwrap(),
&owner_key
));
assert_eq!(ctx.next_partition_id, counters);
}
struct PartitionActivationHarness {
ctx: PartitionScan,
matcher: PatternMatcher,
}
impl PartitionActivationHarness {
fn new() -> Self {
Self::new_with_state_memory(
crate::execution::common::memory::new_unbounded_state_memory(),
)
}
fn new_with_state_memory(state_memory: Arc<MemoryReservation>) -> Self {
let schema = make_test_schema();
let compiled = create_test_pattern();
let resolved_output =
resolve_test_output(&schema, compiled.as_ref(), RowsPerMatch::OneRow);
let ctx = PartitionScan::try_new(
resolved_output,
1000,
crate::config::YieldPolicy::from_test_budget(100),
Arc::clone(&compiled),
1,
false,
None,
ExecutionPartitionId::new(0),
state_memory,
)
.expect("test context should build");
Self {
ctx,
matcher: create_test_matcher(&schema, compiled),
}
}
fn current(&self) -> &ScanContext {
self.ctx.scratch.as_ref().expect("active owner")
}
fn current_mut(&mut self) -> &mut ScanContext {
self.ctx.scratch.as_mut().expect("active owner")
}
fn bind_collection(
&mut self,
partition_id: MatchPartitionId,
head: CollectionHeadGeneration,
) {
let variant = self
.matcher
.compile_variant_for_test(test_normalized_pattern())
.unwrap();
let active =
ActiveVariant::from_pruned(variant, self.matcher.program.base_variant());
let current = self.current_mut();
current.validate_logical_partition(partition_id).unwrap();
current.install_active_variant(active).unwrap();
current
.publish_collection_binding(head, 0, 2, false)
.unwrap();
}
fn activate(
&mut self,
key: &[ScalarValue],
range: Range<usize>,
global_offset: usize,
has_partition_by: bool,
head_generation: CollectionHeadGeneration,
) -> Result<MatchPartitionId> {
self.ctx.has_partition_by = has_partition_by;
let existing = self.ctx.current_scan().and_then(|scratch| {
let binding = scratch.partition.logical().unwrap();
let owner = binding.key.canonical().unwrap();
(owner.scalar_values().unwrap() == key)
.then_some((binding.partition_id, Arc::clone(owner)))
});
let (partition_id, key) = existing.unwrap_or_else(|| {
(
MatchPartitionId::new(self.ctx.next_partition_id),
owned_partition_key(key.to_vec()),
)
});
let descriptor = PartitionDescriptor {
range,
partition_id,
key: key.into(),
ends_partition: false,
};
self.ctx.activate_partition(
&descriptor,
global_offset,
head_generation,
&self.matcher,
)
}
}
#[test]
fn partition_activation_selects_match_number_owner() {
let mut test_case = PartitionActivationHarness::new();
let key = [ScalarValue::Int32(Some(1))];
let head = CollectionHeadGeneration::new(1);
test_case.activate(&key, 0..2, 0, true, head).unwrap();
test_case.current_mut().partition.next_match_number = 42;
test_case
.activate(&key, 0..1, 2, true, CollectionHeadGeneration::new(2))
.unwrap();
assert_eq!(test_case.current().partition.next_match_number, 42);
test_case.ctx.finish_partition();
test_case
.activate(&[ScalarValue::Int32(Some(2))], 0..1, 3, true, head)
.unwrap();
assert_eq!(test_case.current().partition.next_match_number, 1);
}
#[test]
fn partition_activation_failure_stages_preserve_state_and_retry() {
#[derive(Clone, Copy)]
enum Failure {
Memory,
AbsoluteStart,
PartitionId,
}
for failure in [
Failure::Memory,
Failure::AbsoluteStart,
Failure::PartitionId,
] {
const LIMIT: usize = 4 * 1024 * 1024;
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(LIMIT));
let state = Arc::new(MemoryConsumer::new("activation-state").register(&pool));
let mut test_case = PartitionActivationHarness::new_with_state_memory(state);
let key_a = [ScalarValue::Int32(Some(1))];
let head = CollectionHeadGeneration::new(1);
if !matches!(failure, Failure::Memory) {
test_case.activate(&key_a, 0..2, 0, true, head).unwrap();
test_case.ctx.finish_partition();
}
let valid_id = test_case.ctx.next_partition_id;
if matches!(failure, Failure::PartitionId) {
test_case.ctx.next_partition_id = usize::MAX;
}
let target = vec![
ScalarValue::Utf8(Some("wide-retry-key".repeat(8))),
ScalarValue::Decimal128(Some(98765), 20, 4),
];
let range = if matches!(failure, Failure::AbsoluteStart) {
1..2
} else {
0..2
};
let before = scheduler_fact(&test_case.ctx);
let reserved_before = pool.reserved();
let blocker = MemoryConsumer::new("activation-blocker").register(&pool);
if matches!(failure, Failure::Memory) {
blocker.try_grow(LIMIT - reserved_before).unwrap();
}
let offset = if matches!(failure, Failure::AbsoluteStart) {
usize::MAX
} else {
0
};
let error = test_case
.activate(&target, range.clone(), offset, true, head)
.unwrap_err();
assert!(
matches!(error, DataFusionError::ResourcesExhausted(_)),
"{error}"
);
assert_eq!(scheduler_fact(&test_case.ctx), before);
if matches!(failure, Failure::Memory) {
assert_eq!(pool.reserved(), LIMIT);
}
drop(blocker);
if matches!(failure, Failure::Memory) {
assert_eq!(pool.reserved(), reserved_before);
}
test_case.ctx.next_partition_id = valid_id;
let operation = test_case.activate(&target, range, 0, true, head).unwrap();
assert_eq!(operation, MatchPartitionId::new(valid_id));
assert_eq!(test_case.ctx.next_partition_id, valid_id + 1);
assert_eq!(
partition_key_arc(test_case.current())
.scalar_values()
.unwrap(),
target
);
}
}
#[test]
fn partition_activation_resumes_or_recycles_owner_identity() {
#[derive(Clone, Copy)]
enum Lifecycle {
Resume,
Recycle,
}
for lifecycle in [Lifecycle::Resume, Lifecycle::Recycle] {
let mut test_case = PartitionActivationHarness::new();
let key = [ScalarValue::Int32(Some(1))];
let head = CollectionHeadGeneration::new(1);
let first = test_case.activate(&key, 0..2, 0, true, head).unwrap();
assert_eq!(test_case.current().collection.bound_partition_id(), None);
let first_id = test_case
.current()
.partition
.logical()
.unwrap()
.partition_id;
let first_key = Arc::clone(partition_key_arc(test_case.current()));
match lifecycle {
Lifecycle::Resume => {
test_case.bind_collection(first, head);
let next_head = CollectionHeadGeneration::new(2);
let resumed = test_case.activate(&key, 0..2, 0, true, next_head).unwrap();
assert_eq!(resumed, first);
}
Lifecycle::Recycle => {
test_case.bind_collection(first, head);
let current = test_case.current_mut();
current.cursor.row_idx = 9;
current
.scan_state
.resume
.begin_transitions(1, 0, ActiveContainerGeneration::new(1))
.unwrap();
current
.scan_state
.governor
.record_completed(7, || false)
.unwrap();
test_case.ctx.finish_partition();
assert!(
test_case
.ctx
.scratch
.as_deref()
.is_some_and(|scan| scan.partition.logical.is_none())
);
assert_eq!(Arc::strong_count(&first_key), 1);
let operation = test_case.activate(&key, 0..2, 100, true, head).unwrap();
assert_ne!(operation, first);
assert!(test_case.current().collection.is_idle());
}
}
let current = test_case.current();
let logical = current.partition.logical().unwrap();
assert_eq!(
logical.key.canonical().unwrap().scalar_values().unwrap(),
key
);
if matches!(lifecycle, Lifecycle::Recycle) {
assert_ne!(logical.partition_id, first_id);
assert!(!Arc::ptr_eq(partition_key_arc(current), &first_key));
assert_eq!(current.partition.next_match_number, 1);
assert!(current.collection.bound_partition_id().is_none());
assert!(current.active_variant.is_none());
assert_eq!(current.cursor.row_idx, 0);
assert!(current.scan_state.resume.is_start_row());
assert_eq!(current.scan_state.governor.work_since_yield_for_test(), 7);
} else {
assert_eq!(logical.partition_id, first_id);
assert!(Arc::ptr_eq(partition_key_arc(current), &first_key));
}
}
}
#[test]
fn retained_input_includes_open_tail_and_pending_output() {
let mut ctx = create_test_context();
assert_eq!(ctx.min_retained_input_row(0).unwrap(), None);
let mut scratch = scan_context(&create_test_pattern(), 1);
scratch.partition.logical = Some(LogicalPartitionBinding {
partition_id: MatchPartitionId::new(0),
key: shared_empty_partition_key().into(),
});
scratch.cursor.row_idx = 51;
ctx.scratch = Some(Box::new(scratch));
assert_eq!(ctx.min_retained_input_row(3).unwrap(), Some(48));
ctx.accumulator.set_min_buffered_row_for_test(Some(40));
assert_eq!(ctx.min_retained_input_row(0).unwrap(), Some(40));
ctx.finish_partition();
assert_eq!(ctx.min_replay_input_row(0).unwrap(), None);
assert_eq!(ctx.min_retained_input_row(0).unwrap(), Some(40));
}
#[test]
fn post_partition_yield_publishes_committed_match_telemetry_once() -> Result<()> {
let mut ctx = create_test_context();
let compiled = create_test_pattern();
let mut scratch = scan_context(compiled.as_ref(), 1);
scratch.scan_state.governor.record_completed(1, || false)?;
ctx.scratch = Some(Box::new(scratch));
ctx.yield_policy = crate::config::YieldPolicy::from_test_budget(1);
ctx.accumulator.set_matches_total_for_test(3);
let metrics_set = datafusion::physical_plan::metrics::ExecutionPlanMetricsSet::new();
let metrics = PatternMetrics::new_stateful(&metrics_set, 0);
assert!(PartitionScan::take_post_partition_yield_if_due(
ctx.scratch.as_deref_mut(),
&mut ctx.accumulator,
ctx.yield_policy,
&metrics,
true,
));
assert_eq!(metrics.matches_emitted.value(), 3);
assert_eq!(ctx.accumulator.take_matches_total(), 0);
assert!(!PartitionScan::take_post_partition_yield_if_due(
ctx.scratch.as_deref_mut(),
&mut ctx.accumulator,
ctx.yield_policy,
&metrics,
true,
));
assert_eq!(metrics.matches_emitted.value(), 3);
Ok(())
}
#[test]
fn short_partition_clock_probe_keeps_bounded_and_eager_checks() -> Result<()> {
let mut ctx = create_test_context();
let compiled = create_test_pattern();
ctx.scratch = Some(Box::new(scan_context(compiled.as_ref(), 1)));
let policy = crate::config::YieldPolicy::Deadline(std::time::Instant::now());
let metrics_set = datafusion::physical_plan::metrics::ExecutionPlanMetricsSet::new();
let metrics = PatternMetrics::new_stateful(&metrics_set, 0);
for (work, sample_clock, should_yield) in [
(1, true, false),
(254, true, false),
(1, true, true),
(1, false, true),
] {
let scratch = ctx.scratch.as_deref_mut().unwrap();
scratch
.scan_state
.governor
.record_completed(work, || false)?;
assert_eq!(
PartitionScan::take_post_partition_yield_if_due(
Some(scratch),
&mut ctx.accumulator,
policy,
&metrics,
sample_clock,
),
should_yield,
);
}
Ok(())
}
struct DirectDriverCase {
part_values: Vec<u32>,
ranges: Vec<Range<usize>>,
sym_a_flags: Vec<bool>,
end: PhysicalHeadEnd,
flush_threshold: usize,
budget: usize,
disable_compact_paths: bool,
}
struct DirectDriverRun {
yields: usize,
batch_row_counts: Vec<usize>,
counts: Vec<i64>,
first_ids: Vec<i64>,
next_partition_id: usize,
route_scan_direct_linear: usize,
route_scan_continuous: usize,
route_scan_specialized: usize,
output_compact_matches: usize,
}
fn direct_count_first_id_output(
schema: &Schema,
compiled: &CompiledAutomaton,
count_symbol: Option<SymbolId>,
) -> Result<Arc<ExecutableOutputPlan>> {
use crate::core::MatchSummaryField;
use crate::execution::matching::ExecutableDirectCountSummary;
let field = |index, name, data_type, nullable| {
MatchSummaryField::new(index, Arc::new(Field::new(name, data_type, nullable)))
};
ExecutableOutputPlan::try_direct_counts(
schema,
MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
Arc::from([]),
vec![
ExecutableDirectCountSummary::new(
field(0, "n", DataType::Int64, false),
count_symbol,
),
ExecutableDirectCountSummary::new_edge(
field(1, "first_id", DataType::Int64, true),
None,
0,
false,
),
],
compiled,
)
}
fn drain_direct_count_first_id_output(
pending: &mut PendingOutput,
) -> (Vec<usize>, Vec<i64>, Vec<i64>) {
use datafusion::arrow::array::Int64Array;
let mut batch_row_counts = Vec::new();
let mut counts = Vec::new();
let mut first_ids = Vec::new();
while let Some(batch) = pending.pop_front() {
batch_row_counts.push(batch.num_rows());
counts.extend_from_slice(
batch
.column(0)
.as_any()
.downcast_ref::<Int64Array>()
.unwrap()
.values(),
);
first_ids.extend_from_slice(
batch
.column(1)
.as_any()
.downcast_ref::<Int64Array>()
.unwrap()
.values(),
);
}
(batch_row_counts, counts, first_ids)
}
fn run_direct_driver_case(case: DirectDriverCase) -> Result<DirectDriverRun> {
use crate::core::vm::{
AggregateLayout, AggregateValueSource, RegisterLayout, RegisterWriter, SlotInfo,
VmTier,
};
use crate::execution::matching::test_helper::add_count_register;
use crate::execution::matching::test_symbol_programs_with_vm_for_automaton;
use datafusion::arrow::array::{Int64Array, UInt64Array};
let rows = case.part_values.len();
assert_eq!(case.sym_a_flags.len(), rows);
let pattern = NormalizedPattern::Ast(Pattern::Concat(vec![
Pattern::Symbol(Symbol::Named("A".into())),
Pattern::Symbol(Symbol::Named("A".into())),
]));
let compiled = Arc::new(CompiledAutomaton::compile(&pattern, &["A".into()])?);
let sym_a = SymbolId::try_new(1, compiled.num_symbols()).unwrap();
let lane_bit = 1u64 << sym_a.index();
let packed_values: Vec<u64> = case
.sym_a_flags
.iter()
.map(|&flag| if flag { lane_bit } else { 0 })
.collect();
let base_schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::Int64, false),
Field::new("part", DataType::UInt32, false),
Field::new("__mr_symbol_a", DataType::Boolean, false),
Field::new("__mr_lane_mask", DataType::UInt64, false),
]));
let part_col: ArrayRef = Arc::new(UInt32Array::from(case.part_values));
let base_batch = RecordBatch::try_new(
base_schema,
vec![
Arc::new(Int64Array::from_iter_values(0..rows as i64)),
Arc::clone(&part_col),
Arc::new(BooleanArray::from(case.sym_a_flags)),
Arc::new(UInt64Array::from(packed_values)),
],
)?;
let (batch, count_agg, _) = add_count_register(base_batch, sym_a);
let schema = batch.schema();
let lane_col_idx = schema.index_of("__mr_lane_mask")?;
let collection = BatchCollection::try_new(vec![batch], Arc::clone(&schema))?;
let layout = RegisterLayout::builder(
1,
vec![AggregateLayout {
slot: Some(SlotInfo::int64(0)),
value_source: AggregateValueSource::Register { slot: 0 },
..Default::default()
}],
)
.vm_tier(VmTier::Compact)
.try_build()
.unwrap();
let output = direct_count_first_id_output(schema.as_ref(), compiled.as_ref(), None)?;
let mut context = PartitionScan::try_new_for_test(
Arc::clone(&schema),
Arc::clone(&output),
case.flush_threshold,
case.budget,
Arc::clone(&compiled),
1,
)?;
context.has_partition_by = true;
assert!(
context.accumulator.can_append_direct_winner(),
"test output spec must admit ClosedDirectDriver"
);
let metrics_set = datafusion::physical_plan::metrics::ExecutionPlanMetricsSet::new();
let metrics = PatternMetrics::new_stateful(&metrics_set, 0);
let programs = test_symbol_programs_with_vm_for_automaton(
&compiled,
&[],
&[],
vec![vec![RegisterWriter::Count {
aggregate: 0,
input: None,
}]],
layout,
);
let mut config = MatchRecognizeConfig::default();
config.diagnostics.disable_compact_paths = case.disable_compact_paths;
let mut matcher = crate::execution::matching::build_test_matcher(
schema,
pattern,
compiled,
&config,
move |input| {
input.symbols.symbol_programs = programs;
input.aggregate_programs = vec![count_agg];
input.output = output;
},
)?
.with_metrics(&metrics);
matcher.program.packed_lane_column = Some(lane_col_idx);
if !case.disable_compact_paths {
let variant = matcher.program.base_variant();
assert!(
variant
.lane_scan_program()
.is_some_and(|lane| lane.supports_direct_loop()),
"test matcher must admit the direct loop: outcome={:?} has_lane={}",
variant.lane_outcome().rejection(),
variant.lane_scan_program().is_some(),
);
}
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(usize::MAX));
let memory = MemoryConsumer::new("closed-direct-driver").register(&pool);
let partitions = context.prepare_partitions(
&memory,
&case.ranges,
std::slice::from_ref(&part_col),
case.end,
&collection,
&matcher,
)?;
let mut pending = PendingOutput::default();
let mut bound = BoundHead {
stop_on_output: false,
scan: &mut context,
partitions,
collection: &collection,
origin: 0,
};
let mut complete = false;
let mut yields = 0usize;
for _ in 0..1000 {
if bound.advance(ComputeRuntime {
pattern_matcher: &mut matcher,
history_buffer: None,
metrics: &metrics,
pending_output: &mut pending,
})? == ComputeStep::Complete
{
complete = true;
break;
}
yields += 1;
}
assert!(
complete,
"closed direct driver must complete without livelock for budget={}",
case.budget
);
let (batch_row_counts, counts, first_ids) =
drain_direct_count_first_id_output(&mut pending);
context.accumulator.validate_no_pending_builder_tail()?;
Ok(DirectDriverRun {
yields,
batch_row_counts,
counts,
first_ids,
next_partition_id: context.next_partition_id,
route_scan_direct_linear: metrics.route_scan_direct_linear.value(),
route_scan_continuous: metrics.route_scan_continuous.value(),
route_scan_specialized: metrics.route_scan_specialized.value(),
output_compact_matches: metrics.output_compact_matches.value(),
})
}
fn run_direct_driver_open_tail_case(
flush_threshold: usize,
budget: usize,
disable_compact_paths: bool,
) -> Result<DirectDriverRun> {
run_direct_driver_case(DirectDriverCase {
part_values: vec![1u32, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4],
ranges: vec![0..1, 1..5, 5..9, 9..12],
sym_a_flags: vec![
true, true, true, true, true, false, true, true, false, true, true, true,
],
end: PhysicalHeadEnd::OpenTail,
flush_threshold,
budget,
disable_compact_paths,
})
}
#[test]
fn closed_direct_driver_handles_short_partitions_yields_flushes_and_open_tail()
-> Result<()> {
for (budget, flush_threshold) in [(0, 16), (1, 16), (0, 2), (1, 2)] {
let run = run_direct_driver_open_tail_case(flush_threshold, budget, false)?;
if budget == 1 {
assert!(
run.yields > 0,
"tight test budget must exercise cooperative yield"
);
}
assert_eq!(run.route_scan_continuous > 0, budget == 0);
assert!(
run.route_scan_direct_linear > 0,
"closed direct driver should record direct linear scans"
);
if flush_threshold == 16 {
assert_eq!(run.batch_row_counts.len(), 2);
assert_eq!(run.batch_row_counts[0], 3);
}
assert_eq!(run.counts, vec![2, 2, 2, 2]);
assert_eq!(run.first_ids, vec![1, 3, 6, 9]);
assert_eq!(run.next_partition_id, 4);
}
Ok(())
}
#[test]
fn disable_compact_paths_bypasses_direct_linear_loops_with_identical_output() -> Result<()>
{
for budget in [0, 1] {
let enabled = run_direct_driver_open_tail_case(16, budget, false)?;
let disabled = run_direct_driver_open_tail_case(16, budget, true)?;
assert!(
enabled.route_scan_direct_linear > 0,
"default config should use direct-linear loop (budget={budget})"
);
assert_eq!(
disabled.route_scan_direct_linear, 0,
"disable_compact_paths must bypass direct-linear loops (budget={budget})"
);
assert_eq!(
disabled.route_scan_continuous, 0,
"disable_compact_paths must bypass continuous direct scans (budget={budget})"
);
assert!(
disabled.route_scan_specialized > 0,
"disable_compact_paths should keep ordinary Lane enabled (budget={budget})"
);
assert_eq!(
(
disabled.counts,
disabled.first_ids,
disabled.next_partition_id
),
(enabled.counts, enabled.first_ids, enabled.next_partition_id)
);
}
Ok(())
}
#[test]
fn closed_suffix_reuse_does_not_cross_partitions_on_start_skip_yield() -> Result<()> {
use crate::core::vm::RegisterLayout;
use crate::execution::matching::{
ResolvedAfterMatchSkip, test_symbol_programs_with_vm_for_automaton,
};
use datafusion::arrow::array::Int64Array;
let pattern = NormalizedPattern::Ast(Pattern::Repetition(
Box::new(Pattern::Symbol(Symbol::Named("A".into()))),
RepetitionQuantifier::OneOrMore,
));
let compiled = Arc::new(CompiledAutomaton::compile(&pattern, &["A".into()])?);
let part_col: ArrayRef = Arc::new(UInt32Array::from_iter_values(
(0..200).map(|row| u32::from(row >= 100)),
));
let batch = RecordBatch::try_from_iter([
(
"id",
Arc::new(Int64Array::from_iter_values(0..200)) as ArrayRef,
),
("part", Arc::clone(&part_col)),
(
"__mr_symbol_a",
Arc::new(BooleanArray::from(
(0..200)
.map(|row| (90..100).contains(&row) || row >= 190)
.collect::<Vec<_>>(),
)),
),
])?;
let schema = batch.schema();
let output = direct_count_first_id_output(
&schema,
&compiled,
Some(SymbolId::try_new(1, compiled.num_symbols()).unwrap()),
)?;
let programs = test_symbol_programs_with_vm_for_automaton(
&compiled,
&[],
&[],
vec![vec![]],
RegisterLayout::empty_compact(0),
);
let mut config = MatchRecognizeConfig::default();
config.diagnostics.disable_pattern_optimizer = true;
let mut matcher = crate::execution::matching::build_test_matcher(
Arc::clone(&schema),
pattern,
Arc::clone(&compiled),
&config,
|input| {
input.symbols.symbol_programs = programs;
input.after_match_skip = ResolvedAfterMatchSkip::ToNextRow;
input.output = Arc::clone(&output);
},
)?;
assert!(
matcher
.program
.base_variant()
.lane_scan_program()
.unwrap()
.suffix_reuse
.is_some()
);
let collection = BatchCollection::try_new(vec![batch], Arc::clone(&schema))?;
let mut context =
PartitionScan::try_new_for_test(schema, output, 1024, 256, compiled, 1)?;
context.has_partition_by = true;
let metrics = PatternMetrics::new_stateful(
&datafusion::physical_plan::metrics::ExecutionPlanMetricsSet::new(),
0,
);
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(usize::MAX));
let memory = MemoryConsumer::new("closed-suffix-boundary").register(&pool);
let partitions = context.prepare_partitions(
&memory,
&[0..100, 100..200],
&[part_col],
PhysicalHeadEnd::InputEnd,
&collection,
&matcher,
)?;
let mut pending = PendingOutput::default();
let mut bound = BoundHead {
stop_on_output: false,
scan: &mut context,
partitions,
collection: &collection,
origin: 0,
};
assert_eq!(
bound.advance(ComputeRuntime {
pattern_matcher: &mut matcher,
history_buffer: None,
metrics: &metrics,
pending_output: &mut pending,
})?,
ComputeStep::Yield
);
let scratch = bound
.scan
.current_scan()
.expect("second partition is suspended");
assert_eq!(
bound.scan.next_partition_id, 2,
"yielded at row {}",
scratch.cursor.row_idx
);
assert!((100..190).contains(&scratch.cursor.row_idx));
assert_eq!(
bound.scan.min_replay_input_row(0)?,
Some(scratch.cursor.row_idx)
);
assert!(
scratch.direct_suffix.is_none(),
"completed partition's suffix must be discarded"
);
let mut complete = false;
for _ in 0..100 {
if bound.advance(ComputeRuntime {
pattern_matcher: &mut matcher,
history_buffer: None,
metrics: &metrics,
pending_output: &mut pending,
})? == ComputeStep::Complete
{
complete = true;
break;
}
}
assert!(complete, "partition resume must complete without error");
let (_, counts, first_ids) = drain_direct_count_first_id_output(&mut pending);
let actual: Vec<_> = first_ids.into_iter().zip(counts).collect();
let expected: Vec<_> = (90..100)
.map(|row| (row, 100 - row))
.chain((190..200).map(|row| (row, 200 - row)))
.collect();
assert_eq!(actual, expected);
context.accumulator.validate_no_pending_builder_tail()?;
Ok(())
}
#[test]
fn closed_direct_driver_yields_mid_candidate_at_part_start_and_across_completed_partitions()
-> Result<()> {
const PARTITIONS: usize = 16;
const ROWS: usize = PARTITIONS * 2;
let part_values: Vec<u32> = (0..PARTITIONS as u32)
.flat_map(|part| [part, part])
.collect();
let ranges: Vec<Range<usize>> =
(0..PARTITIONS).map(|i| (i * 2)..(i * 2 + 2)).collect();
let expected_first_ids: Vec<i64> = (0..PARTITIONS).map(|i| (i * 2) as i64).collect();
for budget in [1, 16, 32] {
let run = run_direct_driver_case(DirectDriverCase {
part_values: part_values.clone(),
ranges: ranges.clone(),
sym_a_flags: vec![true; ROWS],
end: PhysicalHeadEnd::InputEnd,
flush_threshold: 64,
budget,
disable_compact_paths: false,
})?;
assert!(
run.yields > 0,
"closed direct driver must yield cooperatively for budget={budget}"
);
assert_eq!(run.route_scan_continuous > 0, budget > 1);
assert!(run.route_scan_direct_linear > 0);
assert_eq!(run.output_compact_matches, PARTITIONS);
assert_eq!(run.counts, vec![2; PARTITIONS]);
assert_eq!(run.first_ids, expected_first_ids);
assert_eq!(run.next_partition_id, PARTITIONS);
}
Ok(())
}
#[test]
fn unmatched_finalization_bounds_batch_size_and_pool_memory_on_large_sole_partition()
-> Result<()> {
use datafusion::arrow::array::{Array, Int64Array, StringArray};
const FLUSH_THRESHOLD: usize = 64;
const NUM_BATCHES: usize = 128;
const TOTAL_ROWS: usize = NUM_BATCHES * FLUSH_THRESHOLD;
const POOL_LIMIT: usize = 128 * 1024;
let schema = make_test_schema();
let batches = (0..NUM_BATCHES)
.map(|b| {
let start = (b * FLUSH_THRESHOLD) as u32;
let end = start + FLUSH_THRESHOLD as u32;
RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(UInt32Array::from_iter_values(start..end)) as ArrayRef,
Arc::new(BooleanArray::from(vec![false; FLUSH_THRESHOLD])),
],
)
})
.collect::<std::result::Result<Vec<_>, _>>()?;
let collection = BatchCollection::try_new(batches, Arc::clone(&schema))?;
let pattern = test_normalized_pattern();
let compiled = create_test_pattern();
let rows_per_match = RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched);
let resolved_output =
resolve_test_output(&schema, compiled.as_ref(), rows_per_match.clone());
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(POOL_LIMIT));
let state_memory =
Arc::new(MemoryConsumer::new("partition-scan-bounded-unmatched").register(&pool));
let mut context = PartitionScan::try_new(
resolved_output,
FLUSH_THRESHOLD,
crate::config::YieldPolicy::from_test_budget(64),
Arc::clone(&compiled),
1,
false,
None,
ExecutionPartitionId::new(0),
Arc::clone(&state_memory),
)?;
let mut matcher = create_test_matcher_with_rows(
&schema,
pattern,
Arc::clone(&compiled),
rows_per_match,
);
let prep_memory = crate::execution::common::memory::new_unbounded_state_memory();
let partitions = context.prepare_partitions(
&prep_memory,
std::slice::from_ref(&(0..TOTAL_ROWS)),
&[],
PhysicalHeadEnd::InputEnd,
&collection,
&matcher,
)?;
let metrics_set = datafusion::physical_plan::metrics::ExecutionPlanMetricsSet::new();
let metrics = PatternMetrics::new_stateful(&metrics_set, 0);
let mut pending_output = PendingOutput::new(state_memory.new_empty());
let mut bound = BoundHead {
stop_on_output: false,
scan: &mut context,
partitions,
collection: &collection,
origin: 0,
};
let mut emitted_batches = 0usize;
let mut next_id = 0u32;
let mut yields = 0usize;
let mut complete = false;
for _ in 0..50_000 {
let step = bound.advance(ComputeRuntime {
pattern_matcher: &mut matcher,
history_buffer: None,
metrics: &metrics,
pending_output: &mut pending_output,
})?;
while let Some(batch) = pending_output.pop_front() {
emitted_batches += 1;
assert!(
batch.num_rows() <= FLUSH_THRESHOLD,
"emitted batch had {} rows, exceeding flush_threshold {FLUSH_THRESHOLD}",
batch.num_rows()
);
let ids = batch
.column_by_name("id")
.unwrap()
.as_any()
.downcast_ref::<UInt32Array>()
.unwrap();
let classifiers = batch
.column_by_name(MatchMetadataColumn::Classifier.as_ref())
.unwrap()
.as_any()
.downcast_ref::<StringArray>()
.unwrap();
let match_nums = batch
.column_by_name(MatchMetadataColumn::MatchNumber.as_ref())
.unwrap()
.as_any()
.downcast_ref::<Int64Array>()
.unwrap();
let seq_nums = batch
.column_by_name(MatchMetadataColumn::MatchSequenceNumber.as_ref())
.unwrap()
.as_any()
.downcast_ref::<Int64Array>()
.unwrap();
for row in 0..batch.num_rows() {
assert_eq!(ids.value(row), next_id);
assert!(classifiers.is_null(row));
assert!(match_nums.is_null(row));
assert!(seq_nums.is_null(row));
next_id += 1;
}
}
if step == ComputeStep::Complete {
complete = true;
break;
}
yields += 1;
}
assert!(complete, "bounded unmatched finalization must complete");
assert!(yields > 0, "bounded unmatched finalization must yield");
assert_eq!(next_id as usize, TOTAL_ROWS);
assert_eq!(emitted_batches, NUM_BATCHES);
assert_eq!(
bound.scan.accumulator.min_unfinalized_presence_row()?,
Some(TOTAL_ROWS)
);
drop(bound);
context.accumulator.validate_no_pending_builder_tail()?;
drop((context, matcher, pending_output, state_memory));
assert_eq!(pool.reserved(), 0);
Ok(())
}
#[test]
fn unmatched_finalization_preserves_virtual_eof_match_order_with_bounded_batches()
-> Result<()> {
use datafusion::arrow::array::{Array, Int64Array, StringArray};
const ROWS: usize = 130;
const FLUSH_THRESHOLD: usize = 32;
let schema = make_test_schema();
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(UInt32Array::from_iter_values(0..ROWS as u32)) as ArrayRef,
Arc::new(BooleanArray::from(vec![false; ROWS])),
],
)?;
let collection = BatchCollection::try_new(vec![batch], Arc::clone(&schema))?;
let pattern = NormalizedPattern::Ast(Pattern::Concat(vec![
Pattern::Repetition(
Box::new(Pattern::Symbol(Symbol::Named("A".into()))),
RepetitionQuantifier::ZeroOrMore,
),
Pattern::Symbol(Symbol::End),
]));
let compiled = Arc::new(CompiledAutomaton::compile(&pattern, &["A".into()])?);
let rows_per_match = RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched);
let resolved_output =
resolve_test_output(&schema, compiled.as_ref(), rows_per_match.clone());
let mut context = PartitionScan::try_new_for_test(
Arc::clone(&schema),
resolved_output,
FLUSH_THRESHOLD,
16,
Arc::clone(&compiled),
1,
)?;
let mut matcher = create_test_matcher_with_rows(
&schema,
pattern,
Arc::clone(&compiled),
rows_per_match,
);
let memory = crate::execution::common::memory::new_unbounded_state_memory();
let partitions = context.prepare_partitions(
&memory,
std::slice::from_ref(&(0..ROWS)),
&[],
PhysicalHeadEnd::InputEnd,
&collection,
&matcher,
)?;
let metrics_set = datafusion::physical_plan::metrics::ExecutionPlanMetricsSet::new();
let metrics = PatternMetrics::new_stateful(&metrics_set, 0);
let mut pending_output = PendingOutput::default();
let mut bound = BoundHead {
stop_on_output: false,
scan: &mut context,
partitions,
collection: &collection,
origin: 0,
};
let mut emitted = Vec::new();
let mut complete = false;
for _ in 0..10_000 {
let step = bound.advance(ComputeRuntime {
pattern_matcher: &mut matcher,
history_buffer: None,
metrics: &metrics,
pending_output: &mut pending_output,
})?;
while let Some(batch) = pending_output.pop_front() {
assert!(
batch.num_rows() <= FLUSH_THRESHOLD,
"batch exceeded flush_threshold: {}",
batch.num_rows()
);
emitted.push(batch);
}
if step == ComputeStep::Complete {
complete = true;
break;
}
}
assert!(complete);
assert!(emitted.len() >= 5);
let combined =
datafusion::arrow::compute::concat_batches(&emitted[0].schema(), &emitted)?;
assert_eq!(combined.num_rows(), ROWS);
let ids = combined
.column_by_name("id")
.unwrap()
.as_any()
.downcast_ref::<UInt32Array>()
.unwrap();
let classifiers = combined
.column_by_name(MatchMetadataColumn::Classifier.as_ref())
.unwrap()
.as_any()
.downcast_ref::<StringArray>()
.unwrap();
let match_nums = combined
.column_by_name(MatchMetadataColumn::MatchNumber.as_ref())
.unwrap()
.as_any()
.downcast_ref::<Int64Array>()
.unwrap();
let seq_nums = combined
.column_by_name(MatchMetadataColumn::MatchSequenceNumber.as_ref())
.unwrap()
.as_any()
.downcast_ref::<Int64Array>()
.unwrap();
for row in 0..ROWS {
assert_eq!(ids.value(row), row as u32);
assert!(classifiers.is_null(row));
assert!(match_nums.is_null(row));
assert!(seq_nums.is_null(row));
}
drop(bound);
context.accumulator.validate_no_pending_builder_tail()?;
Ok(())
}
#[test]
fn single_batch_complete_partition_precheck_skips_match_free_and_preserves_multi_batch_and_guards()
-> Result<()> {
use datafusion::arrow::array::UInt64Array;
let pattern = NormalizedPattern::Ast(Pattern::Concat(vec![
Pattern::Symbol(Symbol::Named("A".into())),
Pattern::Symbol(Symbol::Named("B".into())),
]));
let compiled = Arc::new(CompiledAutomaton::compile(
&pattern,
&["A".into(), "B".into()],
)?);
let sym_a = SymbolId::try_new(1, compiled.num_symbols()).unwrap();
let sym_b = SymbolId::try_new(2, compiled.num_symbols()).unwrap();
let bit_a = 1u64 << sym_a.index();
let bit_b = 1u64 << sym_b.index();
let run_case = |a_flags: Vec<bool>,
b_flags: Vec<bool>,
use_packed: bool,
can_skip: bool,
ranges: Vec<Range<usize>>,
end: PhysicalHeadEnd|
-> Result<(usize, usize, usize)> {
let rows = a_flags.len();
let packed: Vec<u64> = a_flags
.iter()
.zip(&b_flags)
.map(|(&a, &b)| (if a { bit_a } else { 0 }) | (if b { bit_b } else { 0 }))
.collect();
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::UInt32, false),
Field::new("part", DataType::UInt32, false),
Field::new("__mr_symbol_a", DataType::Boolean, false),
Field::new("__mr_symbol_b", DataType::Boolean, false),
Field::new("__mr_packed", DataType::UInt64, false),
]));
let mut part_vals = vec![0u32; rows];
for (p_idx, range) in ranges.iter().enumerate() {
for r in range.clone() {
part_vals[r] = p_idx as u32;
}
}
let part_col: ArrayRef = Arc::new(UInt32Array::from(part_vals));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(UInt32Array::from_iter_values(0..rows as u32)),
Arc::clone(&part_col),
Arc::new(BooleanArray::from(a_flags)),
Arc::new(BooleanArray::from(b_flags)),
Arc::new(UInt64Array::from(packed)),
],
)?;
let collection = BatchCollection::try_new(vec![batch], Arc::clone(&schema))?;
let output =
resolve_test_output(&schema, compiled.as_ref(), RowsPerMatch::OneRow);
let mut context = PartitionScan::try_new_for_test(
Arc::clone(&schema),
Arc::clone(&output),
1024,
0,
Arc::clone(&compiled),
1,
)?;
context.has_partition_by = true;
let metrics_set =
datafusion::physical_plan::metrics::ExecutionPlanMetricsSet::new();
let metrics = PatternMetrics::new_stateful(&metrics_set, 0);
let mut config = MatchRecognizeConfig::default();
config.diagnostics.disable_compact_paths = !can_skip;
config.diagnostics.disable_pattern_optimizer = !can_skip;
let mut matcher = crate::execution::matching::build_test_matcher(
Arc::clone(&schema),
pattern.clone(),
Arc::clone(&compiled),
&config,
move |input| {
input.symbols.symbol_columns = vec![
crate::execution::matching::SymbolColumn {
id: sym_a,
column:
crate::execution::matching::ResolvedBoolColumn::new_validated(
2,
),
},
crate::execution::matching::SymbolColumn {
id: sym_b,
column:
crate::execution::matching::ResolvedBoolColumn::new_validated(
3,
),
},
];
input.output = output;
},
)?
.with_metrics(&metrics);
if use_packed {
matcher.program.packed_lane_column = Some(4);
}
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(usize::MAX));
let memory = MemoryConsumer::new("single-batch-precheck").register(&pool);
let partitions = context.prepare_partitions(
&memory,
&ranges,
std::slice::from_ref(&part_col),
end,
&collection,
&matcher,
)?;
let mut pending = PendingOutput::default();
let mut bound = BoundHead {
stop_on_output: false,
scan: &mut context,
partitions,
collection: &collection,
origin: 0,
};
while bound.advance(ComputeRuntime {
pattern_matcher: &mut matcher,
history_buffer: None,
metrics: &metrics,
pending_output: &mut pending,
})? == ComputeStep::Yield
{}
let emitted_rows: usize = pending.iter().map(RecordBatch::num_rows).sum();
Ok((
emitted_rows,
metrics.static_absence_pruned_partitions.value(),
metrics.candidate_starts.value(),
))
};
let n = 1500;
for use_packed in [true, false] {
let (rows, pruned, starts) = run_case(
vec![true; n],
vec![false; n],
use_packed,
true,
std::iter::once(0..n).collect(),
PhysicalHeadEnd::InputEnd,
)?;
assert_eq!(rows, 0, "use_packed={use_packed}");
assert_eq!(
pruned, 1,
"expected 1 pruned partition (use_packed={use_packed})"
);
assert_eq!(
starts, 0,
"expected 0 candidate_starts when skipped (use_packed={use_packed})"
);
}
let mut a = vec![true; 20];
let mut b = vec![false; 20];
a.extend_from_slice(&[true, false]);
b.extend_from_slice(&[false, true]);
a.extend(std::iter::repeat_n(false, 20));
b.extend(std::iter::repeat_n(true, 20));
for use_packed in [true, false] {
let (rows, pruned, starts) = run_case(
a.clone(),
b.clone(),
use_packed,
true,
vec![0..20, 20..22, 22..42],
PhysicalHeadEnd::InputEnd,
)?;
assert_eq!(
rows, 2,
"partition 1 must still emit both rows of A B (use_packed={use_packed})"
);
assert_eq!(
pruned, 2,
"partitions 0 and 2 must be pruned by single-batch precheck (use_packed={use_packed})"
);
assert!(
starts <= 2,
"match-free partitions 0 and 2 must be skipped without candidate starts (starts={starts}, use_packed={use_packed})"
);
}
let (rows, pruned, _starts) = run_case(
vec![true; 16],
vec![false; 16],
true,
false,
std::iter::once(0..16).collect(),
PhysicalHeadEnd::InputEnd,
)?;
assert_eq!(rows, 0);
assert_eq!(
pruned, 0,
"expected 0 pruned partitions when pruning is disabled"
);
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::UInt32, false),
Field::new("part", DataType::UInt32, false),
Field::new("__mr_symbol_a", DataType::Boolean, false),
Field::new("__mr_symbol_b", DataType::Boolean, false),
Field::new("__mr_packed", DataType::UInt64, false),
]));
let output = resolve_test_output(&schema, compiled.as_ref(), RowsPerMatch::OneRow);
let mut context = PartitionScan::try_new_for_test(
Arc::clone(&schema),
Arc::clone(&output),
1024,
0,
Arc::clone(&compiled),
1,
)?;
context.has_partition_by = true;
let metrics_set = datafusion::physical_plan::metrics::ExecutionPlanMetricsSet::new();
let metrics = PatternMetrics::new_stateful(&metrics_set, 0);
let matcher_output = Arc::clone(&output);
let mut matcher = crate::execution::matching::build_test_matcher(
Arc::clone(&schema),
pattern,
Arc::clone(&compiled),
&MatchRecognizeConfig::default(),
move |input| {
input.symbols.symbol_columns = vec![
crate::execution::matching::SymbolColumn {
id: sym_a,
column: crate::execution::matching::ResolvedBoolColumn::new_validated(
2,
),
},
crate::execution::matching::SymbolColumn {
id: sym_b,
column: crate::execution::matching::ResolvedBoolColumn::new_validated(
3,
),
},
];
input.output = matcher_output;
},
)?
.with_metrics(&metrics);
matcher.program.packed_lane_column = Some(4);
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(usize::MAX));
let memory = MemoryConsumer::new("multi-batch-precheck").register(&pool);
let mut pending = PendingOutput::default();
let part0: ArrayRef = Arc::new(UInt32Array::from(vec![7u32; 8]));
let batch0 = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(UInt32Array::from_iter_values(0..8u32)),
Arc::clone(&part0),
Arc::new(BooleanArray::from(vec![true; 8])),
Arc::new(BooleanArray::from(vec![false; 8])),
Arc::new(UInt64Array::from(vec![bit_a; 8])),
],
)?;
let col0 = BatchCollection::try_new(vec![batch0.clone()], Arc::clone(&schema))?;
let p0 = context.prepare_partitions(
&memory,
std::slice::from_ref(&(0..8)),
std::slice::from_ref(&part0),
PhysicalHeadEnd::OpenTail,
&col0,
&matcher,
)?;
let mut bound0 = BoundHead {
stop_on_output: false,
scan: &mut context,
partitions: p0,
collection: &col0,
origin: 0,
};
while bound0.advance(ComputeRuntime {
pattern_matcher: &mut matcher,
history_buffer: None,
metrics: &metrics,
pending_output: &mut pending,
})? == ComputeStep::Yield
{}
drop(bound0);
assert_eq!(
metrics.static_absence_pruned_partitions.value(),
0,
"open-tail head must not be pruned by single-batch precheck"
);
assert!(
context.current_scan().is_some(),
"open-tail head must retain an active partition scan"
);
let part1: ArrayRef = Arc::new(UInt32Array::from(vec![7u32; 16]));
let batch1 = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(UInt32Array::from_iter_values(8..16u32)),
Arc::new(UInt32Array::from(vec![7u32; 8])),
Arc::new(BooleanArray::from(vec![false; 8])),
Arc::new(BooleanArray::from(vec![true; 8])),
Arc::new(UInt64Array::from(vec![bit_b; 8])),
],
)?;
let col1 = BatchCollection::try_new(vec![batch0, batch1], Arc::clone(&schema))?;
let p1 = context.prepare_partitions(
&memory,
std::slice::from_ref(&(0..16)),
std::slice::from_ref(&part1),
PhysicalHeadEnd::InputEnd,
&col1,
&matcher,
)?;
let mut bound1 = BoundHead {
stop_on_output: false,
scan: &mut context,
partitions: p1,
collection: &col1,
origin: 0,
};
while bound1.advance(ComputeRuntime {
pattern_matcher: &mut matcher,
history_buffer: None,
metrics: &metrics,
pending_output: &mut pending,
})? == ComputeStep::Yield
{}
drop(bound1);
let emitted_rows: usize = pending.iter().map(RecordBatch::num_rows).sum();
assert_eq!(
emitted_rows, 2,
"multi-batch continuing partition must emit both rows of A B"
);
assert_eq!(
metrics.static_absence_pruned_partitions.value(),
0,
"continuing multi-batch partition must not be pruned by single-batch precheck"
);
assert!(
context.current_scan().is_none(),
"closing continuing partition must finish its active scan"
);
let mut fresh_context =
PartitionScan::try_new_for_test(schema, output, 1024, 0, compiled, 1)?;
fresh_context.has_partition_by = true;
let p_fresh = fresh_context.prepare_partitions(
&memory,
std::slice::from_ref(&(0..16)),
std::slice::from_ref(&part1),
PhysicalHeadEnd::InputEnd,
&col1,
&matcher,
)?;
let mut fresh_pending = PendingOutput::default();
let mut bound_fresh = BoundHead {
stop_on_output: false,
scan: &mut fresh_context,
partitions: p_fresh,
collection: &col1,
origin: 0,
};
while bound_fresh.advance(ComputeRuntime {
pattern_matcher: &mut matcher,
history_buffer: None,
metrics: &metrics,
pending_output: &mut fresh_pending,
})? == ComputeStep::Yield
{}
drop(bound_fresh);
let fresh_emitted_rows: usize = fresh_pending.iter().map(RecordBatch::num_rows).sum();
assert_eq!(
fresh_emitted_rows, 2,
"fresh multi-batch InputEnd partition must emit both rows of A B"
);
assert_eq!(
metrics.static_absence_pruned_partitions.value(),
0,
"fresh multi-batch InputEnd partition must not be pruned by single-batch precheck"
);
assert!(
fresh_context.current_scan().is_none(),
"fresh multi-batch InputEnd partition must finish its active scan"
);
Ok(())
}