use super::physical_segmentation_helper::{
named, primitive_values, repeated, symbol_batch, symbol_schema,
};
use std::num::NonZeroUsize;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use datafusion::arrow::array::{ArrayRef, BooleanArray, StringArray, UInt32Array};
use datafusion::arrow::datatypes::{
DataType, Field, Int64Type, Schema, SchemaRef, UInt32Type,
};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion_common::{DataFusionError, Result};
use datafusion_execution::memory_pool::MemoryPool;
use datafusion_physical_expr::expressions::Column;
use datafusion_physical_expr_common::sort_expr::PhysicalSortExpr;
use datafusion_physical_plan::SendableRecordBatchStream;
use datafusion_physical_plan::metrics::ExecutionPlanMetricsSet;
use datafusion_physical_plan::stream::RecordBatchStreamAdapter;
use futures::StreamExt;
use crate::config::MatchRecognizeConfig;
use crate::core::{
AfterMatchSkip, EmptyMatchesMode, MatchMetadataColumn, MatchRecognizeOutputSpec,
NavigationOffset, NavigationOffsets, NormalizedPattern, Pattern,
RepetitionQuantifier, RowsPerMatch, Symbol, SymbolId,
};
use crate::execution::common::scheduling::SliceControl;
use crate::execution::matching::TEST_OUTPUT_METADATA;
use crate::execution::matching::program::contracts::{
ExecutableMatchProgramInput, ExecutableSymbolProgramInput,
};
use crate::execution::matching::{
ExecutableMatchProgram, OutputPartitionBindings, RowOutputHarness,
TestCompiledAutomaton, build_test_task_context, seal_test_executable,
test_symbol_programs_for_automaton,
};
use crate::execution::physical::PartitionRetention;
use crate::execution::stream::stateful_stream::match_aware_stream;
use crate::nfa::CompiledAutomaton;
use crate::nfa_executor::{ExecutePatternInput, execute_pattern};
#[derive(Clone)]
struct StreamTestPattern {
normalized_pattern: NormalizedPattern,
automaton: Arc<CompiledAutomaton>,
after_match_skip: AfterMatchSkip,
has_lookahead_defines: bool,
}
struct PreparedTestPattern {
automaton: TestCompiledAutomaton,
has_lookahead_defines: bool,
}
const fn test_lookahead_rows(has_lookahead: bool) -> NavigationOffset {
if has_lookahead {
NavigationOffset::ONE
} else {
NavigationOffset::ZERO
}
}
impl StreamTestPattern {
fn try_untargeted(self) -> Result<PreparedTestPattern> {
self.try_with_target(None)
}
fn try_targeted(self, target: SymbolId) -> Result<PreparedTestPattern> {
self.try_with_target(Some(target))
}
fn try_with_target(self, target: Option<SymbolId>) -> Result<PreparedTestPattern> {
let automaton = TestCompiledAutomaton::try_new(
self.normalized_pattern,
self.automaton,
self.after_match_skip,
target,
)?;
Ok(PreparedTestPattern {
automaton,
has_lookahead_defines: self.has_lookahead_defines,
})
}
fn with_lookahead_defines(mut self) -> Self {
self.has_lookahead_defines = true;
self
}
fn num_symbols(&self) -> usize {
self.automaton.num_symbols()
}
}
fn make_schema(symbols: &[&str]) -> SchemaRef {
symbol_schema(&["id"], symbols)
}
fn make_batch(
schema: &SchemaRef,
ids: &[u32],
symbols: &[(&str, Vec<bool>)],
) -> RecordBatch {
symbol_batch(
schema,
[UInt32Array::from(ids.to_vec())],
symbols.iter().map(|(_, v)| BooleanArray::from(v.clone())),
)
}
fn make_partitioned_schema(symbols: &[&str]) -> SchemaRef {
symbol_schema(&["partition", "id"], symbols)
}
fn make_partitioned_batch(
schema: &SchemaRef,
partitions: &[u32],
ids: &[u32],
symbols: &[(&str, Vec<bool>)],
) -> RecordBatch {
symbol_batch(
schema,
[
UInt32Array::from(partitions.to_vec()),
UInt32Array::from(ids.to_vec()),
],
symbols.iter().map(|(_, v)| BooleanArray::from(v.clone())),
)
}
fn compile_test_pattern(
pattern: Pattern,
symbol_names: Vec<String>,
after_match_skip: AfterMatchSkip,
) -> StreamTestPattern {
let normalized_pattern = NormalizedPattern::Ast(pattern);
let automaton =
Arc::new(CompiledAutomaton::compile(&normalized_pattern, &symbol_names).unwrap());
StreamTestPattern {
normalized_pattern,
automaton,
after_match_skip,
has_lookahead_defines: false,
}
}
fn create_simple_pattern() -> StreamTestPattern {
compile_test_pattern(named("A"), vec!["A".into()], AfterMatchSkip::PastLastRow)
}
fn create_open_tail_pattern() -> StreamTestPattern {
compile_test_pattern(
Pattern::Concat(vec![
named("A"),
repeated("B", RepetitionQuantifier::AtMostOne),
]),
vec!["A".into(), "B".into()],
AfterMatchSkip::PastLastRow,
)
}
fn batch_stream(
schema: &SchemaRef,
batches: impl IntoIterator<Item = Result<RecordBatch>, IntoIter: Send + 'static>,
) -> SendableRecordBatchStream {
Box::pin(RecordBatchStreamAdapter::new(
Arc::clone(schema),
futures::stream::iter(batches),
))
}
fn collect_stream_batches(
mut stream: SendableRecordBatchStream,
) -> Result<Vec<RecordBatch>> {
futures::executor::block_on(async move {
let mut batches = Vec::new();
while let Some(batch) = stream.next().await {
batches.push(batch?);
}
Ok(batches)
})
}
fn prepare_stream_program(
schema: SchemaRef,
pattern: PreparedTestPattern,
output: RowOutputHarness,
) -> Result<Arc<ExecutableMatchProgram>> {
let (normalized_pattern, automaton, after_match_skip) =
pattern.automaton.into_parts();
let output = output.try_build(&schema, &automaton)?;
let symbol_programs = test_symbol_programs_for_automaton(&automaton, &[], 0);
let program = seal_test_executable(ExecutableMatchProgramInput {
input_schema: schema,
normalized_pattern,
symbols: ExecutableSymbolProgramInput {
automaton,
symbol_programs,
relationships: Default::default(),
symbol_columns: vec![],
static_extractions: vec![],
vm_static_inputs: Default::default(),
},
after_match_skip,
output,
aggregate_programs: vec![],
max_define_lookahead_rows: test_lookahead_rows(pattern.has_lookahead_defines),
has_deferred_history_operations: pattern.has_lookahead_defines,
deferred_evaluator_factory: None,
})?;
Ok(Arc::new(program))
}
fn execute_partitioned_test_batches(
schema: SchemaRef,
batches: Vec<RecordBatch>,
pattern: PreparedTestPattern,
output: RowOutputHarness,
flush_threshold: usize,
) -> Result<Vec<RecordBatch>> {
let input_stream: SendableRecordBatchStream =
batch_stream(&schema, batches.into_iter().map(Ok));
let stream = build_partitioned_test_stream(
schema,
input_stream,
pattern,
output,
flush_threshold,
MatchRecognizeConfig::default(),
)?;
collect_stream_batches(stream)
}
fn build_partitioned_test_stream(
schema: SchemaRef,
input_stream: SendableRecordBatchStream,
pattern: PreparedTestPattern,
output: RowOutputHarness,
flush_threshold: usize,
config: MatchRecognizeConfig,
) -> Result<SendableRecordBatchStream> {
build_partitioned_test_stream_with_output_batch_size(
schema,
input_stream,
pattern,
output,
flush_threshold,
None,
config,
)
}
struct StreamExecutionOptions {
output_batch_size: Option<NonZeroUsize>,
flush_threshold: usize,
config: MatchRecognizeConfig,
slice: Option<SliceControl>,
}
fn build_partitioned_test_stream_with_output_batch_size(
schema: SchemaRef,
input_stream: SendableRecordBatchStream,
pattern: PreparedTestPattern,
output: RowOutputHarness,
flush_threshold: usize,
output_batch_size: Option<NonZeroUsize>,
config: MatchRecognizeConfig,
) -> Result<SendableRecordBatchStream> {
build_partitioned_test_stream_with_options(
schema,
input_stream,
pattern,
output,
StreamExecutionOptions {
output_batch_size,
flush_threshold,
config,
slice: None,
},
)
}
fn build_partitioned_test_stream_with_slice(
schema: SchemaRef,
input_stream: SendableRecordBatchStream,
pattern: PreparedTestPattern,
output: RowOutputHarness,
flush_threshold: usize,
config: MatchRecognizeConfig,
slice: SliceControl,
) -> Result<SendableRecordBatchStream> {
build_partitioned_test_stream_with_options(
schema,
input_stream,
pattern,
output,
StreamExecutionOptions {
output_batch_size: None,
flush_threshold,
config,
slice: Some(slice),
},
)
}
fn build_partitioned_test_stream_with_options(
schema: SchemaRef,
input_stream: SendableRecordBatchStream,
pattern: PreparedTestPattern,
output: RowOutputHarness,
options: StreamExecutionOptions,
) -> Result<SendableRecordBatchStream> {
let program = prepare_stream_program(Arc::clone(&schema), pattern, output)?;
let partition_by_sort_keys = vec![PhysicalSortExpr::new_default(Arc::new(
Column::new("partition", 0),
))];
let output_bindings = OutputPartitionBindings::try_new(
schema.as_ref(),
program.output_plan(),
partition_by_sort_keys
.iter()
.map(|key| Arc::clone(&key.expr)),
)?;
let (stream, _) = execute_test_stream(
input_stream,
program,
output_bindings,
partition_by_sort_keys,
options,
)?;
Ok(stream)
}
fn build_no_partition_test_stream(
schema: SchemaRef,
input_stream: SendableRecordBatchStream,
pattern: StreamTestPattern,
output: RowOutputHarness,
config: MatchRecognizeConfig,
) -> Result<(SendableRecordBatchStream, Arc<dyn MemoryPool>)> {
let program = prepare_stream_program(schema, pattern.try_untargeted()?, output)?;
execute_test_stream(
input_stream,
program,
Default::default(),
vec![],
StreamExecutionOptions {
output_batch_size: None,
flush_threshold: 64,
config,
slice: None,
},
)
}
fn execute_test_stream(
input_stream: SendableRecordBatchStream,
program: Arc<ExecutableMatchProgram>,
output_bindings: OutputPartitionBindings,
partition_by_sort_keys: Vec<PhysicalSortExpr>,
options: StreamExecutionOptions,
) -> Result<(SendableRecordBatchStream, Arc<dyn MemoryPool>)> {
let task_context = build_test_task_context("test", "test-session");
let pool = Arc::clone(&task_context.runtime_env().memory_pool);
let retention = PartitionRetention::for_program(program.as_ref());
let input = ExecutePatternInput {
input: crate::execution::stream::MatchInput::Ordered(input_stream),
program,
output_bindings,
partition_by_sort_keys,
retention,
candidate_start_core_rows: None,
output_batch_size: options.output_batch_size,
flush_threshold: options.flush_threshold,
config: options.config,
metrics_set: ExecutionPlanMetricsSet::new(),
task_context,
partition: 0,
};
let stream: SendableRecordBatchStream = match options.slice {
Some(slice) => Box::pin(match_aware_stream(input, slice)?),
None => execute_pattern(input)?,
};
Ok((stream, pool))
}
fn channel_input(
schema: &SchemaRef,
) -> (
futures::channel::mpsc::UnboundedSender<Result<RecordBatch>>,
SendableRecordBatchStream,
) {
let (sender, receiver) = futures::channel::mpsc::unbounded();
(
sender,
Box::pin(RecordBatchStreamAdapter::new(Arc::clone(schema), receiver)),
)
}
fn counted_input(
schema: &SchemaRef,
input: impl futures::Stream<Item = Result<RecordBatch>> + Send + 'static,
) -> (SendableRecordBatchStream, Arc<AtomicUsize>) {
let polls = Arc::new(AtomicUsize::new(0));
let observed = Arc::clone(&polls);
let mut input = Box::pin(input);
let counted = futures::stream::poll_fn(move |cx| {
observed.fetch_add(1, Ordering::Relaxed);
futures::Stream::poll_next(input.as_mut(), cx)
});
(
Box::pin(RecordBatchStreamAdapter::new(Arc::clone(schema), counted)),
polls,
)
}
fn collect_stream_batches_with_poll_limit(
mut stream: SendableRecordBatchStream,
poll_limit: usize,
) -> Result<Vec<RecordBatch>> {
let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
let mut batches = Vec::new();
for _ in 0..poll_limit {
match stream.as_mut().poll_next(&mut cx) {
std::task::Poll::Ready(Some(Ok(batch))) => batches.push(batch),
std::task::Poll::Ready(Some(Err(error))) => return Err(error),
std::task::Poll::Ready(None) => return Ok(batches),
std::task::Poll::Pending => {}
}
}
panic!("pattern stream exceeded the {poll_limit}-poll progress bound");
}
fn next_ready_item(
stream: &mut SendableRecordBatchStream,
cx: &mut std::task::Context<'_>,
) -> Option<Result<RecordBatch>> {
(0..256)
.find_map(|_| match stream.as_mut().poll_next(cx) {
std::task::Poll::Ready(item) => Some(item),
std::task::Poll::Pending => None,
})
.expect("ready test_case input exceeded 256 cooperative polls")
}
fn collect_string_values(
batches: &[RecordBatch],
column_idx: usize,
) -> Vec<Option<String>> {
batches
.iter()
.flat_map(|batch| {
batch
.column(column_idx)
.as_any()
.downcast_ref::<StringArray>()
.expect("string column")
.iter()
.map(|value| value.map(str::to_owned))
.collect::<Vec<_>>()
})
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct EndAnchorOutputRow {
partition: Option<u32>,
id: Option<u32>,
classifier: Option<String>,
match_number: Option<i64>,
sequence_number: Option<i64>,
}
fn unmatched_then_end_anchor(
partition: u32,
ids: impl IntoIterator<Item = u32>,
) -> Vec<EndAnchorOutputRow> {
ids.into_iter()
.map(|id| EndAnchorOutputRow {
partition: Some(partition),
id: Some(id),
classifier: None,
match_number: None,
sequence_number: None,
})
.chain(std::iter::once(EndAnchorOutputRow {
partition: Some(partition),
id: None,
classifier: None,
match_number: Some(1),
sequence_number: Some(1),
}))
.collect()
}
fn collect_end_anchor_output_rows(batches: &[RecordBatch]) -> Vec<EndAnchorOutputRow> {
let partitions = primitive_values::<UInt32Type>(batches, 0);
let ids = primitive_values::<UInt32Type>(batches, 1);
let classifiers = collect_string_values(batches, 2);
let match_numbers = primitive_values::<Int64Type>(batches, 3);
let sequence_numbers = primitive_values::<Int64Type>(batches, 4);
let len = partitions.len();
assert_eq!(ids.len(), len);
assert_eq!(classifiers.len(), len);
assert_eq!(match_numbers.len(), len);
assert_eq!(sequence_numbers.len(), len);
(0..len)
.map(|row| EndAnchorOutputRow {
partition: partitions[row],
id: ids[row],
classifier: classifiers[row].clone(),
match_number: match_numbers[row],
sequence_number: sequence_numbers[row],
})
.collect()
}
fn end_anchor_output_program(rows_per_match: RowsPerMatch) -> RowOutputHarness {
RowOutputHarness::new(
MatchRecognizeOutputSpec::new(
vec![0, 1],
TEST_OUTPUT_METADATA.to_vec(),
vec!["A".into()],
),
Arc::from([SymbolId::try_new(1, 2).unwrap()]),
rows_per_match,
)
}
fn match_number_output_program() -> RowOutputHarness {
RowOutputHarness::new(
MatchRecognizeOutputSpec::new(
vec![],
vec![MatchMetadataColumn::MatchNumber],
vec![],
),
Arc::from([]),
RowsPerMatch::OneRow,
)
}
fn compile_false_a_end_anchor(after_match_skip: AfterMatchSkip) -> StreamTestPattern {
compile_test_pattern(
Pattern::Concat(vec![
repeated("A", RepetitionQuantifier::ZeroOrMore),
Pattern::Symbol(Symbol::End),
]),
vec!["A".into()],
after_match_skip,
)
}
struct CountingWake(AtomicUsize);
impl std::task::Wake for CountingWake {
fn wake(self: Arc<Self>) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
#[test]
fn empty_batches_and_partition_boundaries_do_not_create_matches() -> Result<()> {
let schema = make_partitioned_schema(&["A", "B", "C"]);
for (partitions, same_key) in [([1, 2, 3], false), ([1, 1, 1], true)] {
let empty = RecordBatch::new_empty(Arc::clone(&schema));
let input = make_partitioned_batch(
&schema,
&partitions,
&[1, 2, 3],
&[
("A", vec![true, false, false]),
("B", vec![false, true, false]),
("C", vec![false, false, true]),
],
);
let mode = RowsPerMatch::AllRows(EmptyMatchesMode::Show);
let pattern = compile_test_pattern(
Pattern::Concat(vec![named("A"), named("B"), named("C")]),
vec!["A".into(), "B".into(), "C".into()],
AfterMatchSkip::ToNextRow,
);
let output = RowOutputHarness::new(
MatchRecognizeOutputSpec::new(
vec![1],
vec![
MatchMetadataColumn::Classifier,
MatchMetadataColumn::MatchNumber,
MatchMetadataColumn::MatchSequenceNumber,
],
vec![],
),
Arc::from([]),
mode,
);
let batches = execute_partitioned_test_batches(
Arc::clone(&schema),
vec![empty.clone(), input, empty],
pattern.try_untargeted()?,
output,
1,
)?;
let actual = primitive_values::<UInt32Type>(&batches, 0)
.into_iter()
.zip(collect_string_values(&batches, 1))
.zip(primitive_values::<Int64Type>(&batches, 2))
.zip(primitive_values::<Int64Type>(&batches, 3))
.map(|(((id, classifier), number), sequence)| {
(id, classifier, number, sequence)
})
.collect::<Vec<_>>();
let expected = if same_key {
vec![
(Some(1), Some("A".into()), Some(1), Some(1)),
(Some(2), Some("B".into()), Some(1), Some(2)),
(Some(3), Some("C".into()), Some(1), Some(3)),
]
} else {
vec![]
};
assert_eq!(actual, expected);
}
Ok(())
}
#[test]
fn production_stream_publishes_partial_output_before_polling_later_input() -> Result<()> {
let schema = make_partitioned_schema(&["A", "B"]);
let mut first = Some(make_partitioned_batch(
&schema,
&[1, 1, 1],
&[1, 2, 3],
&[("A", vec![true; 3]), ("B", vec![false; 3])],
));
let mut later = Some(make_partitioned_batch(
&schema,
&[1, 1, 1],
&[4, 5, 6],
&[("A", vec![true; 3]), ("B", vec![false; 3])],
));
let release_input = Arc::new(AtomicBool::new(false));
let gate = Arc::clone(&release_input);
let input = futures::stream::poll_fn(move |_| {
if let Some(batch) = first.take() {
return std::task::Poll::Ready(Some(Ok(batch)));
}
if !gate.load(Ordering::Relaxed) {
return std::task::Poll::Pending;
}
std::task::Poll::Ready(later.take().map(Ok))
});
let (input_stream, upstream_polls) = counted_input(&schema, input);
let mut stream = build_partitioned_test_stream_with_output_batch_size(
schema,
input_stream,
create_open_tail_pattern().try_untargeted()?,
match_number_output_program(),
3,
NonZeroUsize::new(65_536),
MatchRecognizeConfig::default(),
)?;
let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
let Some(Ok(first_output)) = next_ready_item(&mut stream, &mut cx) else {
panic!("a committed partial head must be visible while later input is withheld");
};
assert_eq!(
first_output.column(0).get_buffer_memory_size(),
2 * size_of::<i64>(),
"a partial batch must release unused coalescing capacity"
);
assert_eq!(
primitive_values::<Int64Type>(std::slice::from_ref(&first_output), 0),
vec![Some(1), Some(2)]
);
assert_eq!(upstream_polls.load(Ordering::Relaxed), 1);
release_input.store(true, Ordering::Relaxed);
let mut output = vec![first_output];
output.extend(collect_stream_batches(stream)?);
assert_eq!(
primitive_values::<Int64Type>(&output, 0),
(1..=6).map(Some).collect::<Vec<_>>()
);
Ok(())
}
#[test]
fn production_stream_partial_output_preserves_zero_column_rows() -> Result<()> {
let schema = make_partitioned_schema(&["A", "B"]);
let batch = make_partitioned_batch(
&schema,
&[1, 1, 1],
&[1, 2, 3],
&[("A", vec![true; 3]), ("B", vec![false; 3])],
);
let input = batch_stream(&schema, [Ok(batch)]);
let output = RowOutputHarness::new(
MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
Arc::from([]),
RowsPerMatch::OneRow,
);
let stream = build_partitioned_test_stream_with_output_batch_size(
schema,
input,
create_open_tail_pattern().try_untargeted()?,
output,
3,
NonZeroUsize::new(65_536),
MatchRecognizeConfig::default(),
)?;
let batches = collect_stream_batches(stream)?;
assert_eq!(
batches
.iter()
.map(RecordBatch::num_rows)
.collect::<Vec<_>>(),
vec![2, 1]
);
assert!(batches.iter().all(|batch| batch.num_columns() == 0));
Ok(())
}
#[test]
fn production_stream_preserves_complete_output_batches() -> Result<()> {
let schema = make_partitioned_schema(&["A"]);
let batch = make_partitioned_batch(
&schema,
&[1, 1, 1, 1, 2],
&[1, 2, 3, 4, 5],
&[("A", vec![true; 5])],
);
let input_stream = batch_stream(&schema, [Ok(batch)]);
let stream = build_partitioned_test_stream_with_output_batch_size(
schema,
input_stream,
create_simple_pattern().try_untargeted()?,
match_number_output_program(),
2,
NonZeroUsize::new(4),
MatchRecognizeConfig::default(),
)?;
let output = collect_stream_batches(stream)?;
assert_eq!(
output.iter().map(RecordBatch::num_rows).collect::<Vec<_>>(),
vec![4, 1]
);
assert_eq!(
output
.iter()
.map(|batch| batch.column(0).get_buffer_memory_size())
.collect::<Vec<_>>(),
vec![4 * size_of::<i64>(), size_of::<i64>()],
"full batches retain their target size; the final tail is compact"
);
assert_eq!(
primitive_values::<Int64Type>(&output, 0),
vec![Some(1), Some(2), Some(3), Some(4), Some(1)]
);
Ok(())
}
#[test]
fn committed_output_precedes_upstream_error_with_and_without_coalescing() -> Result<()> {
for output_batch_size in [None, NonZeroUsize::new(4)] {
let schema = make_partitioned_schema(&["A", "B"]);
let batch = make_partitioned_batch(
&schema,
&[1, 1, 1],
&[1, 2, 3],
&[("A", vec![true; 3]), ("B", vec![false; 3])],
);
let owner = Arc::downgrade(batch.column(1));
let marker = "upstream error after committed output";
let (input, polls) = counted_input(
&schema,
futures::stream::iter([
Ok(batch),
Err(DataFusionError::Execution(marker.into())),
]),
);
let mut stream = build_partitioned_test_stream_with_output_batch_size(
schema,
input,
create_open_tail_pattern().try_untargeted()?,
match_number_output_program(),
3,
output_batch_size,
MatchRecognizeConfig::default(),
)?;
let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
let Some(Ok(output)) = next_ready_item(&mut stream, &mut cx) else {
panic!("committed output must precede another upstream poll");
};
assert_eq!(
primitive_values::<Int64Type>(&[output], 0),
vec![Some(1), Some(2)]
);
assert_eq!(polls.load(Ordering::Relaxed), 1);
let Some(Err(error)) = next_ready_item(&mut stream, &mut cx) else {
panic!("upstream error must follow committed output");
};
assert!(error.to_string().contains(marker), "{error}");
assert!(
owner.upgrade().is_none(),
"failure must release input history"
);
for _ in 0..2 {
assert!(matches!(
stream.as_mut().poll_next(&mut cx),
std::task::Poll::Ready(None)
));
}
assert_eq!(
polls.load(Ordering::Relaxed),
2,
"terminal stream repolled input"
);
}
Ok(())
}
#[test]
fn upstream_error_poisons_stream_and_releases_resources() -> Result<()> {
let pattern = create_simple_pattern();
let schema = make_schema(&["A"]);
let first_ids: ArrayRef = Arc::new(UInt32Array::from_iter_values(1..=1));
let retained_owner = Arc::downgrade(&first_ids);
let first = RecordBatch::try_new(
Arc::clone(&schema),
vec![first_ids, Arc::new(BooleanArray::from(vec![true]))],
)?;
let marker = "injected upstream failure";
let upstream_polls = Arc::new(AtomicUsize::new(0));
let observed_polls = Arc::clone(&upstream_polls);
let (upstream_tx, upstream) = futures::channel::mpsc::unbounded();
upstream_tx.unbounded_send(Ok(first)).unwrap();
let upstream = upstream.inspect(move |_| {
observed_polls.fetch_add(1, Ordering::Relaxed);
});
let input: SendableRecordBatchStream =
Box::pin(RecordBatchStreamAdapter::new(Arc::clone(&schema), upstream));
let output_spec = MatchRecognizeOutputSpec::new(
vec![0],
MatchMetadataColumn::public_output().to_vec(),
vec!["A".to_owned()],
);
let output = RowOutputHarness::new(
output_spec,
Arc::from([SymbolId::try_new(1, pattern.num_symbols()).unwrap()]),
RowsPerMatch::OneRow,
);
let (stream, pool) = build_no_partition_test_stream(
Arc::clone(&schema),
input,
pattern,
output,
MatchRecognizeConfig::default(),
)?;
let mut stream = stream;
let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
assert!(matches!(
stream.as_mut().poll_next(&mut cx),
std::task::Poll::Pending
));
assert_eq!(upstream_polls.load(Ordering::Relaxed), 1);
assert!(retained_owner.upgrade().is_some());
assert!(pool.reserved() > 0);
upstream_tx
.unbounded_send(Err(DataFusionError::Execution(marker.to_owned())))
.unwrap();
upstream_tx
.unbounded_send(Ok(make_batch(&schema, &[2], &[("A", vec![true])])))
.unwrap();
let Some(Err(error)) = next_ready_item(&mut stream, &mut cx) else {
panic!("stream must return the upstream failure before any output");
};
assert!(error.to_string().contains(marker), "{error}");
assert_eq!(upstream_polls.load(Ordering::Relaxed), 2);
assert!(retained_owner.upgrade().is_none());
assert_eq!(pool.reserved(), 0);
for _ in 0..2 {
assert!(matches!(
stream.as_mut().poll_next(&mut cx),
std::task::Poll::Ready(None)
));
}
assert_eq!(
upstream_polls.load(Ordering::Relaxed),
2,
"stream retried upstream after terminal failure"
);
Ok(())
}
#[test]
fn threshold_aligned_partitions_close_before_the_next_open_head() -> Result<()> {
let schema = make_partitioned_schema(&["A"]);
let partitions = (0..20).map(|row| (row / 4).min(3)).collect::<Vec<_>>();
let ids = (0..20).collect::<Vec<_>>();
for (all_match, rows_per_match, slice_micros) in [
(true, RowsPerMatch::OneRow, 0),
(false, RowsPerMatch::OneRow, 0),
(
false,
RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched),
1,
),
] {
let input = make_partitioned_batch(
&schema,
&partitions,
&ids,
&[("A", (0..20).map(|row| all_match || row % 2 == 0).collect())],
);
let input_batches = (0..20)
.step_by(4)
.map(|row| input.slice(row, 4))
.collect::<Vec<_>>();
let label = format!(
"{rows_per_match:?}, slice_micros {slice_micros}, all_match {all_match}"
);
let with_unmatched = matches!(
rows_per_match,
RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched)
);
let pattern = create_simple_pattern();
let output = RowOutputHarness::new(
MatchRecognizeOutputSpec::new(
vec![0, 1],
vec![MatchMetadataColumn::MatchNumber],
vec![],
),
Arc::from([]),
rows_per_match,
);
let input_stream =
batch_stream(&schema, input_batches.clone().into_iter().map(Ok));
let mut config = MatchRecognizeConfig::default();
config.limits.yield_slice_micros = slice_micros;
let stream = build_partitioned_test_stream(
Arc::clone(&schema),
input_stream,
pattern.try_untargeted()?,
output,
4,
config,
)?;
let batches = collect_stream_batches_with_poll_limit(stream, 512)?;
let mut actual = primitive_values::<UInt32Type>(&batches, 0)
.into_iter()
.zip(primitive_values::<UInt32Type>(&batches, 1))
.zip(primitive_values::<Int64Type>(&batches, 2))
.collect::<Vec<_>>();
if with_unmatched {
actual.sort_unstable_by_key(|((_, id), _)| *id);
}
let expected = (0..20)
.filter(|row| all_match || row % 2 == 0 || with_unmatched)
.map(|row| {
let partition = partitions[row as usize];
let offset = row - partition * 4;
let number = if all_match {
offset + 1
} else {
offset / 2 + 1
};
(
(Some(partition), Some(row)),
(all_match || row % 2 == 0).then_some(i64::from(number)),
)
})
.collect::<Vec<_>>();
assert_eq!(actual, expected, "{label}");
}
Ok(())
}
#[test]
fn an_endless_greedy_candidate_keeps_growing_history() -> Result<()> {
use std::task::Poll;
let schema = make_schema(&["A"]);
let pattern = compile_test_pattern(
repeated("A", RepetitionQuantifier::OneOrMore),
vec!["A".into()],
AfterMatchSkip::PastLastRow,
);
let (upstream_tx, input) = channel_input(&schema);
let mut config = MatchRecognizeConfig::default();
config.limits.yield_slice_micros = 0;
let (mut stream, pool) = build_no_partition_test_stream(
Arc::clone(&schema),
input,
pattern,
match_number_output_program(),
config,
)?;
let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
let mut first_owner = None;
let mut previous_bytes = 0;
for head in 0..3 {
let ids = (head * 64 + 1..=(head + 1) * 64).collect::<Vec<_>>();
let batch = make_batch(&schema, &ids, &[("A", vec![true; 64])]);
if head == 0 {
first_owner = Some(Arc::downgrade(batch.column(0)));
}
upstream_tx.unbounded_send(Ok(batch)).unwrap();
assert!(matches!(stream.as_mut().poll_next(&mut cx), Poll::Pending));
let bytes = pool.reserved();
assert!(
bytes > previous_bytes,
"history must grow across live heads"
);
previous_bytes = bytes;
}
assert!(
first_owner.unwrap().upgrade().is_some(),
"the live candidate still needs its first input batch"
);
Ok(())
}
#[test]
fn changed_partition_keys_close_buffered_and_suspended_tails() -> Result<()> {
use std::task::Poll;
for old_rows in [16, 64] {
for (before, after) in [
(Some(1), Some(2)),
(None, Some(2)),
(Some(1), None),
(None, None),
(Some(1), Some(1)),
] {
let schema = Arc::new(Schema::new(vec![
Field::new("partition", DataType::UInt32, true),
Field::new("id", DataType::UInt32, false),
Field::new("__mr_symbol_a", DataType::Boolean, false),
]));
let batch = |key, start, rows| {
RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(UInt32Array::from(vec![key; rows])),
Arc::new(UInt32Array::from_iter_values(
start..start + rows as u32,
)),
Arc::new(BooleanArray::from(vec![true; rows])),
],
)
};
let rows_per_match = RowsPerMatch::AllRows(EmptyMatchesMode::Show);
let pattern = compile_test_pattern(
repeated("A", RepetitionQuantifier::OneOrMore),
vec!["A".into()],
AfterMatchSkip::PastLastRow,
);
let output = RowOutputHarness::new(
MatchRecognizeOutputSpec::new(
vec![0, 1],
vec![MatchMetadataColumn::MatchNumber],
vec![],
),
Arc::from([]),
rows_per_match,
);
let (tx, input) = channel_input(&schema);
let mut config = MatchRecognizeConfig::default();
config.limits.yield_slice_micros = 0;
let mut stream = build_partitioned_test_stream(
Arc::clone(&schema),
input,
pattern.try_untargeted()?,
output,
64,
config,
)?;
let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
tx.unbounded_send(Ok(batch(before, 1, old_rows)?)).unwrap();
assert!(matches!(stream.as_mut().poll_next(&mut cx), Poll::Pending));
tx.unbounded_send(Ok(batch(after, old_rows as u32 + 1, 1)?))
.unwrap();
let mut batches = Vec::new();
if before != after {
let Some(Ok(output)) = next_ready_item(&mut stream, &mut cx) else {
panic!(
"a changed key must close the buffered or suspended greedy partition"
);
};
assert_eq!(
primitive_values::<UInt32Type>(std::slice::from_ref(&output), 1),
(1..=old_rows as u32).map(Some).collect::<Vec<_>>()
);
batches.push(output);
}
assert!(matches!(stream.as_mut().poll_next(&mut cx), Poll::Pending));
drop(tx);
batches.extend(collect_stream_batches(stream)?);
assert_eq!(
primitive_values::<UInt32Type>(&batches, 1),
(1..=old_rows as u32 + 1).map(Some).collect::<Vec<_>>()
);
assert_eq!(
primitive_values::<UInt32Type>(&batches, 0),
[vec![before; old_rows], vec![after]].concat()
);
assert_eq!(
primitive_values::<Int64Type>(&batches, 2),
vec![Some(1); old_rows + 1]
);
}
}
Ok(())
}
#[test]
fn changed_key_flushes_short_and_suspended_unmatched_tails() -> Result<()> {
use std::task::Poll;
for old_rows in [1, 2, 64, 65] {
let schema = make_partitioned_schema(&["A"]);
let rows_per_match = RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched);
let pattern = compile_test_pattern(
repeated("A", RepetitionQuantifier::Exactly(3)),
vec!["A".into()],
AfterMatchSkip::PastLastRow,
);
let output = RowOutputHarness::new(
MatchRecognizeOutputSpec::new(
vec![0, 1],
vec![MatchMetadataColumn::MatchNumber],
vec![],
),
Arc::from([]),
rows_per_match,
);
let (tx, input) = channel_input(&schema);
let mut config = MatchRecognizeConfig::default();
config.limits.yield_slice_micros = 0;
let mut stream = build_partitioned_test_stream(
Arc::clone(&schema),
input,
pattern.try_untargeted()?,
output,
64,
config,
)?;
let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
let first_rows = old_rows.min(64);
tx.unbounded_send(Ok(make_partitioned_batch(
&schema,
&vec![1; first_rows],
&(1..=first_rows as u32).collect::<Vec<_>>(),
&[("A", vec![true; first_rows])],
)))
.unwrap();
let mut batches = Vec::new();
if old_rows >= 64 {
let Some(Ok(output)) = next_ready_item(&mut stream, &mut cx) else {
panic!("the threshold head must publish its 63 complete rows");
};
assert_eq!(output.num_rows(), 63);
batches.push(output);
}
assert!(matches!(stream.as_mut().poll_next(&mut cx), Poll::Pending));
if old_rows == 65 {
tx.unbounded_send(Ok(make_partitioned_batch(
&schema,
&[1],
&[65],
&[("A", vec![true])],
)))
.unwrap();
assert!(matches!(stream.as_mut().poll_next(&mut cx), Poll::Pending));
}
tx.unbounded_send(Ok(make_partitioned_batch(
&schema,
&[2],
&[old_rows as u32 + 1],
&[("A", vec![true])],
)))
.unwrap();
let Some(Ok(output)) = next_ready_item(&mut stream, &mut cx) else {
panic!("a closed unmatched tail must precede the new Pending partition");
};
assert_eq!(output.num_rows(), old_rows % 3);
assert_eq!(
primitive_values::<Int64Type>(std::slice::from_ref(&output), 2),
vec![None; old_rows % 3]
);
batches.push(output);
assert!(matches!(stream.as_mut().poll_next(&mut cx), Poll::Pending));
drop(tx);
batches.extend(collect_stream_batches(stream)?);
assert_eq!(
primitive_values::<UInt32Type>(&batches, 1),
(1..=old_rows as u32 + 1).map(Some).collect::<Vec<_>>()
);
let expected = (0..old_rows + 1)
.map(|row| (row < old_rows / 3 * 3).then_some((row / 3 + 1) as i64))
.collect::<Vec<_>>();
assert_eq!(primitive_values::<Int64Type>(&batches, 2), expected);
}
Ok(())
}
#[test]
fn production_stream_buffers_open_lookahead_until_partition_boundary() -> Result<()> {
use std::task::Poll;
let schema = make_partitioned_schema(&["A"]);
let open_batch =
make_partitioned_batch(&schema, &[1, 1, 1], &[1, 2, 3], &[("A", vec![true; 3])]);
let boundary_batch =
make_partitioned_batch(&schema, &[2], &[4], &[("A", vec![true])]);
let pattern =
compile_test_pattern(named("A"), vec!["A".into()], AfterMatchSkip::PastLastRow)
.with_lookahead_defines();
let (upstream_tx, input_stream) = channel_input(&schema);
let mut config = MatchRecognizeConfig::default();
config.limits.yield_slice_micros = 0;
let mut stream = build_partitioned_test_stream(
schema,
input_stream,
pattern.try_untargeted()?,
match_number_output_program(),
3,
config,
)?;
let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
upstream_tx.unbounded_send(Ok(open_batch)).unwrap();
assert!(matches!(stream.as_mut().poll_next(&mut cx), Poll::Pending));
upstream_tx
.unbounded_send(Ok(RecordBatch::new_empty(boundary_batch.schema())))
.unwrap();
assert!(matches!(stream.as_mut().poll_next(&mut cx), Poll::Pending));
upstream_tx.unbounded_send(Ok(boundary_batch)).unwrap();
let Some(Ok(output)) = next_ready_item(&mut stream, &mut cx) else {
panic!("a known partition boundary must release lookahead output");
};
assert_eq!(
primitive_values::<Int64Type>(&[output], 0),
vec![Some(1), Some(2), Some(3)]
);
drop(upstream_tx);
assert_eq!(
primitive_values::<Int64Type>(&collect_stream_batches(stream)?, 0),
vec![Some(1)]
);
Ok(())
}
#[test]
fn production_stream_publishes_bounded_prefix_of_unbounded_alternation() -> Result<()> {
use std::task::Poll;
let schema = make_partitioned_schema(&["A"]);
let pattern = compile_test_pattern(
Pattern::Alternation(vec![
named("A"),
repeated("A", RepetitionQuantifier::OneOrMore),
]),
vec!["A".into()],
AfterMatchSkip::PastLastRow,
);
let output = RowOutputHarness::new(
MatchRecognizeOutputSpec::new(
vec![1],
vec![MatchMetadataColumn::MatchNumber],
vec![],
),
Arc::from([]),
RowsPerMatch::OneRow,
);
let (upstream_tx, input_stream) = channel_input(&schema);
let mut config = MatchRecognizeConfig::default();
config.limits.yield_slice_micros = 0;
let mut stream = build_partitioned_test_stream(
Arc::clone(&schema),
input_stream,
pattern.try_untargeted()?,
output,
3,
config,
)?;
let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
upstream_tx
.unbounded_send(Ok(make_partitioned_batch(
&schema,
&[1, 1, 1],
&[1, 2, 3],
&[("A", vec![true, true, false])],
)))
.unwrap();
let Some(Ok(first)) = next_ready_item(&mut stream, &mut cx) else {
panic!("unbounded alternation must release its safe open prefix");
};
assert_eq!(
primitive_values::<UInt32Type>(std::slice::from_ref(&first), 0),
vec![Some(1), Some(2)]
);
assert_eq!(
primitive_values::<Int64Type>(&[first], 1),
vec![Some(1), Some(2)]
);
assert!(matches!(stream.as_mut().poll_next(&mut cx), Poll::Pending));
Ok(())
}
#[tokio::test(flavor = "current_thread")]
async fn ready_output_bursts_cooperate_with_slicing_disabled() -> Result<()> {
const ROWS: usize = 513;
let schema = make_partitioned_schema(&["A"]);
let expected = (0..ROWS as u32).collect::<Vec<_>>();
let batch = make_partitioned_batch(
&schema,
&vec![1; ROWS],
&expected,
&[("A", vec![true; ROWS])],
);
let rows_per_match = RowsPerMatch::AllRows(EmptyMatchesMode::Show);
let pattern = compile_test_pattern(
Pattern::Concat(vec![
repeated("A", RepetitionQuantifier::OneOrMore),
Pattern::Symbol(Symbol::End),
]),
vec!["A".into()],
AfterMatchSkip::PastLastRow,
);
let output = RowOutputHarness::new(
MatchRecognizeOutputSpec::new(vec![1], vec![], vec![]),
Arc::from([]),
rows_per_match,
);
for output_batch_size in [None, NonZeroUsize::new(2)] {
let input_stream = batch_stream(&schema, [Ok(batch.clone())]);
let mut config = MatchRecognizeConfig::default();
config.limits.yield_slice_micros = 0;
let mut stream = build_partitioned_test_stream_with_output_batch_size(
Arc::clone(&schema),
input_stream,
pattern.clone().try_untargeted()?,
output.clone(),
1,
output_batch_size,
config,
)?;
let mut actual = Vec::new();
let mut yielded_during_output = false;
while let Some(batch) = futures::future::poll_fn(|cx| {
let value = stream.poll_next_unpin(cx);
if value.is_pending() && !actual.is_empty() && actual.len() < ROWS {
yielded_during_output = true;
}
value
})
.await
{
let batch = batch?;
actual.extend_from_slice(
batch
.column(0)
.as_any()
.downcast_ref::<UInt32Array>()
.unwrap()
.values(),
);
}
assert_eq!(actual, expected);
assert!(
yielded_during_output,
"native cooperation must interrupt ready output with slicing disabled"
);
}
Ok(())
}
fn sorted_end_anchor_rows(batches: &[RecordBatch]) -> Vec<EndAnchorOutputRow> {
let mut rows = collect_end_anchor_output_rows(batches);
rows.sort_by_key(|row| (row.partition, row.id.is_none(), row.id.unwrap_or(u32::MAX)));
rows
}
#[test]
fn false_a_end_anchor_preserves_output_modes_at_final_head() -> Result<()> {
use AfterMatchSkip::{PastLastRow, ToNextRow};
use EmptyMatchesMode::{Omit, Show, WithUnmatched};
use RowsPerMatch::{AllRows, OneRow};
let schema = make_partitioned_schema(&["A"]);
let batches = &[
make_partitioned_batch(&schema, &[10, 10], &[1, 2], &[("A", vec![false; 2])]),
make_partitioned_batch(&schema, &[10], &[3], &[("A", vec![false])]),
make_partitioned_batch(&schema, &[20, 20], &[4, 5], &[("A", vec![false; 2])]),
make_partitioned_batch(&schema, &[20], &[6], &[("A", vec![false])]),
][..];
let empty = [
unmatched_then_end_anchor(10, []),
unmatched_then_end_anchor(20, []),
]
.concat();
let empty = empty.as_slice();
let unmatched = [
unmatched_then_end_anchor(10, 1..=3),
unmatched_then_end_anchor(20, 4..=6),
]
.concat();
for (label, skip, mode, slice, input, expected) in [
("one row", PastLastRow, OneRow, 0, batches, empty),
("show empty", ToNextRow, AllRows(Show), 1, batches, empty),
("omit empty", PastLastRow, AllRows(Omit), 0, batches, &[]),
(
"with unmatched",
ToNextRow,
AllRows(WithUnmatched),
0,
batches,
unmatched.as_slice(),
),
("empty input", ToNextRow, AllRows(Show), 1, &[], &[]),
] {
let input: Vec<_> = input.iter().cloned().map(Ok).collect();
let input = batch_stream(&schema, input);
let mut config = MatchRecognizeConfig::default();
config.limits.yield_slice_micros = slice;
config.diagnostics.disable_pattern_optimizer = true;
let stream = build_partitioned_test_stream(
Arc::clone(&schema),
input,
compile_false_a_end_anchor(skip).try_untargeted()?,
end_anchor_output_program(mode),
2,
config,
)?;
let outputs = collect_stream_batches_with_poll_limit(stream, 512)?;
assert_eq!(sorted_end_anchor_rows(&outputs), expected, "{label}");
}
Ok(())
}
#[test]
fn false_a_end_anchor_waits_for_finality_and_streams_known_partition_boundary()
-> Result<()> {
let schema = make_partitioned_schema(&["A"]);
let (sender, input_stream) = channel_input(&schema);
let mut config = MatchRecognizeConfig::default();
config.limits.yield_slice_micros = 0;
let stream = build_partitioned_test_stream(
schema.clone(),
input_stream,
compile_false_a_end_anchor(AfterMatchSkip::ToNextRow).try_untargeted()?,
end_anchor_output_program(RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched)),
1,
config,
)?;
let mut stream = stream;
let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
sender
.unbounded_send(Ok(make_partitioned_batch(
&schema,
&[10, 10],
&[1, 2],
&[("A", vec![false, false])],
)))
.unwrap();
assert!(matches!(
stream.as_mut().poll_next(&mut cx),
std::task::Poll::Pending
));
sender
.unbounded_send(Ok(make_partitioned_batch(
&schema,
&[10],
&[3],
&[("A", vec![false])],
)))
.unwrap();
assert!(matches!(
stream.as_mut().poll_next(&mut cx),
std::task::Poll::Pending
));
sender
.unbounded_send(Ok(make_partitioned_batch(
&schema,
&[20, 20],
&[4, 5],
&[("A", vec![false, false])],
)))
.unwrap();
let std::task::Poll::Ready(Some(Ok(first_partition_head))) =
stream.as_mut().poll_next(&mut cx)
else {
panic!("the known partition-10 boundary must make its end anchor final");
};
let mut first_partition_batches = vec![first_partition_head];
loop {
match stream.as_mut().poll_next(&mut cx) {
std::task::Poll::Ready(Some(Ok(batch))) => {
first_partition_batches.push(batch)
}
std::task::Poll::Ready(Some(Err(error))) => return Err(error),
std::task::Poll::Ready(None) => {
panic!("the stream terminated before partition 20 arrived")
}
std::task::Poll::Pending => break,
}
}
assert_eq!(
sorted_end_anchor_rows(&first_partition_batches),
unmatched_then_end_anchor(10, 1..=3)
);
sender
.unbounded_send(Ok(make_partitioned_batch(
&schema,
&[20],
&[6],
&[("A", vec![false])],
)))
.unwrap();
assert!(matches!(
stream.as_mut().poll_next(&mut cx),
std::task::Poll::Pending
));
drop(sender);
let final_outputs = collect_stream_batches_with_poll_limit(stream, 128)?;
assert_eq!(
sorted_end_anchor_rows(&final_outputs),
unmatched_then_end_anchor(20, 4..=6)
);
Ok(())
}
#[test]
fn retained_head_yields_do_not_poll_late_input_or_change_finality() -> Result<()> {
let schema = make_partitioned_schema(&["A"]);
let first = make_partitioned_batch(
&schema,
&[vec![10; 32], vec![20]].concat(),
&(1..=33).collect::<Vec<_>>(),
&[("A", vec![false; 33])],
);
let late = make_partitioned_batch(
&schema,
&[20, 20],
&[34, 35],
&[("A", vec![false, false])],
);
let (sender, input) = channel_input(&schema);
sender.unbounded_send(Ok(first)).unwrap();
sender.unbounded_send(Ok(late)).unwrap();
let (input, upstream_polls) = counted_input(&schema, input);
let mut config = MatchRecognizeConfig::default();
config.diagnostics.disable_pattern_optimizer = true;
let mut stream = build_partitioned_test_stream_with_slice(
Arc::clone(&schema),
input,
compile_false_a_end_anchor(AfterMatchSkip::ToNextRow).try_untargeted()?,
end_anchor_output_program(RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched)),
64,
config,
SliceControl::for_test_budget(NonZeroUsize::MIN),
)?;
let wake_count = Arc::new(CountingWake(AtomicUsize::new(0)));
let waker = std::task::Waker::from(Arc::clone(&wake_count));
let mut cx = std::task::Context::from_waker(&waker);
assert!(matches!(
stream.as_mut().poll_next(&mut cx),
std::task::Poll::Pending
));
assert_eq!(upstream_polls.load(Ordering::SeqCst), 1);
assert!(wake_count.0.load(Ordering::SeqCst) > 0);
let first_output = (0..16_384)
.find_map(|_| {
let wakes_before = wake_count.0.load(Ordering::SeqCst);
match stream.as_mut().poll_next(&mut cx) {
std::task::Poll::Pending => {
assert_eq!(
upstream_polls.load(Ordering::SeqCst),
1,
"a retained head polled queued late input while yielding"
);
assert!(wake_count.0.load(Ordering::SeqCst) > wakes_before);
None
}
std::task::Poll::Ready(Some(Ok(batch))) => {
assert_eq!(
upstream_polls.load(Ordering::SeqCst),
1,
"late input changed the known-boundary head before publication"
);
Some(Ok(batch))
}
std::task::Poll::Ready(Some(Err(error))) => Some(Err(error)),
std::task::Poll::Ready(None) => {
panic!("the stream ended before publishing partition 10")
}
}
})
.expect("retained head exceeded the bounded yield schedule")?;
assert_eq!(
sorted_end_anchor_rows(&[first_output]),
unmatched_then_end_anchor(10, 1..=32)
);
drop(sender);
let tail = collect_stream_batches_with_poll_limit(stream, 16_384)?;
assert_eq!(
upstream_polls.load(Ordering::SeqCst),
3,
"late batch and EOF must each be polled exactly once"
);
assert_eq!(
sorted_end_anchor_rows(&tail),
unmatched_then_end_anchor(20, 33..=35)
);
Ok(())
}
#[test]
fn first_and_last_symbol_skip_choose_distinct_restarts_across_flush() -> Result<()> {
let schema = make_partitioned_schema(&["A", "C", "B"]);
let input = vec![
make_partitioned_batch(
&schema,
&[1, 1],
&[1, 2],
&[
("A", vec![true, true]),
("C", vec![false, true]),
("B", vec![false, false]),
],
),
make_partitioned_batch(
&schema,
&[1, 1, 1, 1],
&[3, 4, 5, 6],
&[
("A", vec![true, false, false, false]),
("C", vec![true, false, false, false]),
("B", vec![false, true, true, true]),
],
),
];
for first in [true, false] {
let skip = if first {
AfterMatchSkip::ToFirst("C".into())
} else {
AfterMatchSkip::ToLast("C".into())
};
let pattern = compile_test_pattern(
Pattern::Concat(vec![
named("A"),
repeated("C", RepetitionQuantifier::OneOrMore),
repeated("B", RepetitionQuantifier::Exactly(3)),
]),
vec!["A".into(), "C".into(), "B".into()],
skip,
);
let output = RowOutputHarness::new(
MatchRecognizeOutputSpec::new(
vec![1],
vec![
MatchMetadataColumn::Classifier,
MatchMetadataColumn::MatchNumber,
MatchMetadataColumn::MatchSequenceNumber,
],
vec![],
),
Arc::from([]),
RowsPerMatch::OneRow,
);
let batches = execute_partitioned_test_batches(
Arc::clone(&schema),
input.clone(),
pattern.try_targeted(SymbolId::try_new(2, 4).unwrap())?,
output,
2,
)?;
let mut expected = vec![
(1, "A", 1, 1),
(2, "C", 1, 2),
(3, "C", 1, 3),
(4, "B", 1, 4),
(5, "B", 1, 5),
(6, "B", 1, 6),
];
if first {
expected.extend([
(2, "A", 2, 1),
(3, "C", 2, 2),
(4, "B", 2, 3),
(5, "B", 2, 4),
(6, "B", 2, 5),
]);
}
let classifiers = collect_string_values(&batches, 1);
let actual = primitive_values::<UInt32Type>(&batches, 0)
.into_iter()
.zip(classifiers.iter().map(Option::as_deref))
.zip(primitive_values::<Int64Type>(&batches, 2))
.zip(primitive_values::<Int64Type>(&batches, 3))
.map(|(((id, classifier), number), sequence)| {
(id, classifier, number, sequence)
})
.collect::<Vec<_>>();
let expected = expected
.into_iter()
.map(|(id, classifier, number, sequence)| {
(Some(id), Some(classifier), Some(number), Some(sequence))
})
.collect::<Vec<_>>();
let target = if first { "FIRST" } else { "LAST" };
assert_eq!(actual, expected, "SKIP TO {target} C");
}
Ok(())
}
#[test]
fn start_anchor_does_not_match_physical_flush_boundary() -> Result<()> {
let schema = make_partitioned_schema(&["A"]);
for (label, first_values, second_values, expected) in [
(
"true logical start",
vec![true, true],
vec![true, true],
vec![Some(1)],
),
(
"false logical start, true later head",
vec![false, false],
vec![true, true],
vec![],
),
] {
let batch1 =
make_partitioned_batch(&schema, &[1, 1], &[1, 2], &[("A", first_values)]);
let batch2 =
make_partitioned_batch(&schema, &[1, 1], &[3, 4], &[("A", second_values)]);
let pattern = compile_test_pattern(
Pattern::Concat(vec![Pattern::Symbol(Symbol::Start), named("A")]),
vec!["A".into()],
AfterMatchSkip::PastLastRow,
);
let batches = execute_partitioned_test_batches(
schema.clone(),
vec![batch1, batch2],
pattern.try_untargeted()?,
match_number_output_program(),
2,
)?;
assert_eq!(
primitive_values::<Int64Type>(&batches, 0),
expected,
"{label}"
);
}
Ok(())
}
#[test]
fn next_buffer_survives_input_flush_boundary() -> Result<()> {
let schema = make_partitioned_schema(&["A"]);
let batch1 = make_partitioned_batch(&schema, &[1], &[1], &[("A", vec![true])]);
let batch2 = make_partitioned_batch(&schema, &[1], &[2], &[("A", vec![false])]);
let pattern =
compile_test_pattern(named("A"), vec!["A".into()], AfterMatchSkip::PastLastRow);
let output = RowOutputHarness::new(
MatchRecognizeOutputSpec::with_validated_navigation_offsets(
vec![1],
vec![
MatchMetadataColumn::MatchNumber,
MatchMetadataColumn::MatchSequenceNumber,
],
vec![],
NavigationOffsets::new(NavigationOffset::ZERO, NavigationOffset::ONE),
),
Arc::from([]),
RowsPerMatch::OneRow,
);
let batches = execute_partitioned_test_batches(
schema,
vec![batch1, batch2],
pattern.try_untargeted()?,
output,
1,
)?;
assert_eq!(
primitive_values::<UInt32Type>(&batches, 0),
vec![Some(1), Some(2)]
);
assert_eq!(
primitive_values::<Int64Type>(&batches, 1),
vec![Some(1), Some(1)]
);
assert_eq!(
primitive_values::<Int64Type>(&batches, 2),
vec![Some(1), Some(i64::MAX - 1)]
);
Ok(())
}
#[test]
fn reluctant_lane_emits_from_open_head_before_polling_upstream_error() -> Result<()> {
for general in [false, true] {
let schema = make_partitioned_schema(&["A"]);
let batch = make_partitioned_batch(&schema, &[1], &[1], &[("A", vec![true])]);
let (input, polls) = counted_input(
&schema,
futures::stream::iter([
Ok(batch),
Err(DataFusionError::Execution("must not poll batch 1".into())),
]),
);
let pattern = compile_test_pattern(
repeated("A", RepetitionQuantifier::OneOrMoreReluctant),
vec!["A".into()],
AfterMatchSkip::PastLastRow,
);
let mut config = MatchRecognizeConfig::default();
config.diagnostics.disable_compact_paths = general;
let mut stream = build_partitioned_test_stream_with_output_batch_size(
schema,
input,
pattern.try_untargeted()?,
match_number_output_program(),
1,
None,
config,
)?;
let mut cx = std::task::Context::from_waker(futures::task::noop_waker_ref());
let Some(Ok(output)) = next_ready_item(&mut stream, &mut cx) else {
panic!("A+? must commit on the first physical row, general={general}");
};
assert_eq!(primitive_values::<Int64Type>(&[output], 0), vec![Some(1)]);
assert_eq!(polls.load(Ordering::Relaxed), 1);
drop(stream);
assert_eq!(polls.load(Ordering::Relaxed), 1);
}
Ok(())
}