use super::*;
use crate::execution::matching::path::Sym;
use crate::core::{
MatchRecognizeOutputSpec, NavigationOffsets, NormalizedPattern, Pattern, Symbol,
};
use crate::execution::matching::ExecutableOutputPlan;
use crate::execution::matching::static_test_support::TEST_OUTPUT_METADATA;
use datafusion::arrow::array::{
Array, BooleanArray, Int32Array, Int64Array, StringArray,
};
use datafusion::arrow::datatypes::{DataType, Field};
use datafusion::execution::memory_pool::{
MemoryConsumer, MemoryPool, UnboundedMemoryPool,
};
#[derive(Clone, Debug, PartialEq, Eq)]
struct ObservedRow {
id: Option<i32>,
classifier: Option<String>,
match_number: Option<i64>,
sequence_number: Option<i64>,
}
fn input_schema() -> SchemaRef {
Arc::new(Schema::new(vec![
Field::new("id", DataType::Int32, false),
Field::new(crate::core::symbol_col_name("A"), DataType::Boolean, false),
]))
}
fn input_batch(schema: &SchemaRef, ids: &[i32]) -> RecordBatch {
RecordBatch::try_new(
Arc::clone(schema),
vec![
Arc::new(Int32Array::from(ids.to_vec())),
Arc::new(BooleanArray::from(vec![true; ids.len()])),
],
)
.unwrap()
}
fn collection(schema: &SchemaRef, batch: RecordBatch) -> BatchCollection {
BatchCollection::try_new(vec![batch], Arc::clone(schema)).unwrap()
}
fn accumulator(
schema: &SchemaRef,
pattern: Pattern,
symbol_names: Vec<String>,
rows_per_match: RowsPerMatch,
flush_threshold: usize,
max_prev_offset: usize,
max_next_offset: usize,
) -> MatchAccumulator {
let pattern = NormalizedPattern::Ast(pattern);
let compiled = Arc::new(CompiledAutomaton::compile(&pattern, &symbol_names).unwrap());
let output_spec = MatchRecognizeOutputSpec::with_validated_navigation_offsets(
vec![0],
TEST_OUTPUT_METADATA.to_vec(),
vec![],
NavigationOffsets::try_from_raw(max_prev_offset, max_next_offset)
.expect("test offsets must fit the navigation domain"),
);
let resolved_output = ExecutableOutputPlan::try_rows(
schema.as_ref(),
output_spec,
Arc::from([]),
rows_per_match,
compiled.as_ref(),
)
.unwrap();
MatchAccumulator::try_new_unbounded(compiled, flush_threshold, resolved_output)
.unwrap()
}
fn named_step(row: usize) -> PathStep {
PathStep {
row: AbsoluteRow::new(u64::try_from(row).unwrap()),
sym: Sym::from_index(1),
excluded: false,
}
}
#[allow(clippy::too_many_arguments)]
fn record_named_match(
accumulator: &mut MatchAccumulator,
match_id: u64,
rows: &[usize],
partition: Range<usize>,
global_offset: usize,
batches: &BatchCollection,
pending_output: &mut PendingOutput,
history: Option<&SharedHistoryBuffer>,
) {
let path = rows.iter().copied().map(named_step).collect::<Vec<_>>();
accumulator
.record_test_match(
match_id,
&path,
MatchEmissionContext {
partition,
global_offset,
batches,
pending_output,
history,
},
)
.unwrap();
}
fn observations(batch: &RecordBatch) -> Vec<ObservedRow> {
let ids = batch
.column_by_name("id")
.unwrap()
.as_any()
.downcast_ref::<Int32Array>()
.unwrap();
let classifiers = batch
.column_by_name(MatchMetadataColumn::Classifier.as_ref())
.unwrap()
.as_any()
.downcast_ref::<StringArray>()
.unwrap();
let match_numbers = batch
.column_by_name(MatchMetadataColumn::MatchNumber.as_ref())
.unwrap()
.as_any()
.downcast_ref::<Int64Array>()
.unwrap();
let sequence_numbers = batch
.column_by_name(MatchMetadataColumn::MatchSequenceNumber.as_ref())
.unwrap()
.as_any()
.downcast_ref::<Int64Array>()
.unwrap();
(0..batch.num_rows())
.map(|row| ObservedRow {
id: ids.is_valid(row).then(|| ids.value(row)),
classifier: classifiers
.is_valid(row)
.then(|| classifiers.value(row).to_string()),
match_number: match_numbers
.is_valid(row)
.then(|| match_numbers.value(row)),
sequence_number: sequence_numbers
.is_valid(row)
.then(|| sequence_numbers.value(row)),
})
.collect()
}
type PhysicalRowSpec<'a> = (i32, Option<&'a str>, Option<i64>, Option<i64>);
fn physical_rows(rows: &[PhysicalRowSpec<'_>]) -> Vec<ObservedRow> {
rows.iter()
.map(|&(id, label, number, sequence)| ObservedRow {
id: Some(id),
classifier: label.map(str::to_owned),
match_number: number,
sequence_number: sequence,
})
.collect()
}
fn all_observations(batches: &PendingOutput) -> Vec<ObservedRow> {
batches.iter().flat_map(observations).collect()
}
#[test]
fn presence_survives_repeated_flushes_and_physical_heads() {
let schema = input_schema();
let first_head = collection(&schema, input_batch(&schema, &[0, 1, 2, 3]));
let second_head = collection(&schema, input_batch(&schema, &[4, 5, 6, 7]));
let mut accumulator = accumulator(
&schema,
Pattern::Symbol(Symbol::Named("A".into())),
vec!["A".into()],
RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched),
1,
0,
0,
);
let mut output = PendingOutput::default();
for (head, origin, matches) in [
(&first_head, 0, vec![(1, vec![1, 2]), (2, vec![2])]),
(&second_head, 4, vec![(3, vec![4, 6]), (4, vec![6])]),
] {
let before = output.len();
for (number, rows) in matches {
record_named_match(
&mut accumulator,
number,
&rows,
0..8,
origin,
head,
&mut output,
None,
);
}
assert_eq!(
output.len() - before,
3,
"threshold1 flushes every matched row"
);
accumulator.max_processed_row = origin + 4;
output
.push_back(
accumulator
.flush_collection(head, origin, None, true)
.unwrap()
.unwrap(),
)
.unwrap();
assert_eq!(
accumulator.min_unfinalized_presence_row().unwrap(),
Some(origin + 4)
);
}
assert_eq!(
all_observations(&output),
physical_rows(&[
(1, Some("A"), Some(1), Some(1)),
(2, Some("A"), Some(1), Some(2)),
(2, Some("A"), Some(2), Some(1)),
(0, None, None, None),
(3, None, None, None),
(4, Some("A"), Some(3), Some(1)),
(6, Some("A"), Some(3), Some(2)),
(6, Some("A"), Some(4), Some(1)),
(5, None, None, None),
(7, None, None, None),
])
);
}
#[test]
fn out_of_bounds_empty_position_is_rejected_and_physical_empty_marks_its_row() {
let schema = input_schema();
for ids in [&[][..], &[10, 11][..]] {
let batches = collection(&schema, input_batch(&schema, ids));
let mut accumulator = accumulator(
&schema,
Pattern::Symbol(Symbol::End),
vec![],
RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched),
64,
0,
0,
);
let mut pending = PendingOutput::default();
let end = ids.len();
let path = [PathStep {
row: AbsoluteRow::new(end as u64),
sym: Sym::Empty,
excluded: false,
}];
let err = accumulator
.record_test_match(
1,
&path,
MatchEmissionContext {
partition: 0..end,
global_offset: 0,
batches: &batches,
pending_output: &mut pending,
history: None,
},
)
.unwrap_err();
assert!(
err.to_string()
.contains("empty control step at invalid absolute row"),
"{err}"
);
assert_eq!(accumulator.take_matches_total(), 0);
assert!(pending.is_empty());
assert_eq!(accumulator.row_presence.reserved_bytes(), 0);
if !ids.is_empty() {
let physical_empty = [PathStep {
row: AbsoluteRow::new(0),
sym: Sym::Empty,
excluded: false,
}];
accumulator
.record_test_match(
1,
&physical_empty,
MatchEmissionContext {
partition: 0..end,
global_offset: 0,
batches: &batches,
pending_output: &mut pending,
history: None,
},
)
.unwrap();
let output = accumulator
.flush_collection(&batches, 0, None, false)
.unwrap()
.unwrap();
assert_eq!(
observations(&output),
physical_rows(&[(10, None, Some(1), Some(1))])
);
accumulator.max_processed_row = end;
let unmatched = accumulator
.flush_collection(&batches, 0, None, true)
.unwrap();
assert_eq!(
observations(&unmatched.unwrap()),
physical_rows(&[(11, None, None, None)])
);
}
}
}
#[test]
fn presence_survives_retained_prev_next_history() {
let schema = input_schema();
let first_batch = input_batch(&schema, &[0, 1, 2, 3]);
let second_batch = input_batch(&schema, &[4, 5, 6, 7]);
let first_head = collection(&schema, first_batch.clone());
let second_head = collection(&schema, second_batch.clone());
let pool: Arc<dyn MemoryPool> = Arc::new(UnboundedMemoryPool::default());
let reservation = MemoryConsumer::new("row-presence-history-test").register(&pool);
let mut history = SharedHistoryBuffer::new(Arc::clone(&schema), reservation);
history.append(first_batch).unwrap();
history.append(second_batch).unwrap();
for flush_threshold in [1, 64] {
let case = format!("threshold-{flush_threshold}");
let mut accumulator = accumulator(
&schema,
Pattern::Symbol(Symbol::Named("A".into())),
vec!["A".into()],
RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched),
flush_threshold,
1,
1,
);
let mut output = PendingOutput::default();
record_named_match(
&mut accumulator,
1,
&[2],
0..8,
0,
&first_head,
&mut output,
Some(&history),
);
match flush_threshold {
1 => assert_eq!(output.len(), 3, "{case} per-row flush count"),
64 => assert!(output.is_empty(), "{case}"),
_ => unreachable!("fixed threshold table"),
}
if flush_threshold == 64 {
assert_eq!(accumulator.min_buffered_row(), Some(1), "{case}");
output
.push_back(
accumulator
.flush_collection(&second_head, 4, Some(&history), false)
.unwrap()
.expect("retained history gathers PREV, match, and NEXT rows"),
)
.unwrap();
} else {
assert!(accumulator.is_empty(), "{case} left an output tail");
}
let final_head = BatchCollection::empty(Arc::clone(&schema));
accumulator.max_processed_row = 8;
output
.push_back(
accumulator
.flush_collection(&final_head, 8, Some(&history), true)
.unwrap()
.expect("the empty final head drains historical unmatched rows"),
)
.unwrap();
assert_eq!(accumulator.min_unfinalized_presence_row().unwrap(), Some(8));
assert!(
accumulator
.flush_collection(&final_head, 8, Some(&history), true)
.unwrap()
.is_none()
);
assert_eq!(
all_observations(&output),
physical_rows(&[
(1, None, Some(1), Some(-1)),
(2, Some("A"), Some(1), Some(1)),
(3, None, Some(1), Some(i64::MAX - 1)),
(0, None, None, None),
(1, None, None, None),
(3, None, None, None),
(4, None, None, None),
(5, None, None, None),
(6, None, None, None),
(7, None, None, None),
]),
"{case}"
);
}
}