use std::sync::Arc;
use crate::core::{AbsoluteRow, MatchMetadataColumn};
use crate::execution::storage::PendingOutput;
use datafusion::arrow::array::{
Array, ArrayBuilder, ArrayRef, BooleanBuilder, Int64Builder, StringBuilder,
new_null_array,
};
#[cfg(test)]
use datafusion::arrow::datatypes::Schema;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion_common::{DataFusionError, Result, internal_err};
use datafusion_execution::memory_pool::MemoryReservation;
use crate::execution::common::coordinates::{
absolute_row_from_usize, absolute_row_to_usize,
};
use crate::execution::common::memory::try_reserve_accounted;
use crate::execution::common::progress::{COARSE_WORK_BATCH_SIZE, CoarseWorkBatch};
use crate::execution::matching::{
ExecutableDirectCountSummary, ExecutableRowStreamPlan, PartitionPassthrough,
};
use crate::execution::storage::collection::BatchCollection;
use crate::execution::storage::history_buffer::SharedHistoryBuffer;
use crate::execution::storage::row_presence::RowPresence;
use super::encoder::{EncodedClassifier, EncodedOutputRow};
use super::{GatherPlan, OutputRowRef};
mod gather;
mod metadata;
pub(in crate::execution::storage) use gather::VIRTUAL_DEFAULT_COORD;
pub(crate) use gather::{
canonical_interleave_type, contains_run_end_encoded, retype_gather_data,
};
mod assembly;
mod reduction;
enum SummaryOutputStorage {
Ordinary,
DirectCounts {
automaton: Arc<crate::nfa::CompiledAutomaton>,
summaries: Arc<[ExecutableDirectCountSummary]>,
columns: Vec<DirectCountColumn>,
reductions: Option<reduction::ReductionColumns>,
row_capacity: usize,
},
}
struct DirectCountColumn {
values: Vec<u64>,
memory: MemoryReservation,
prepared_array: Option<(ArrayRef, MemoryReservation)>,
}
const CLASSIFIER_RESERVATION_CHUNK: usize = 1024;
pub(in crate::execution::storage) struct OutputBatchBuilder {
class_builder: Option<StringBuilder>,
class_bytes: usize,
class_reserved: usize,
match_num_builder: Option<Int64Builder>,
seq_builder: Option<Int64Builder>,
excluded_builder: Option<BooleanBuilder>,
classifier_bits_builders: Vec<BooleanBuilder>,
summary_output: SummaryOutputStorage,
stream: Arc<ExecutableRowStreamPlan>,
row_refs: Vec<OutputRowRef>,
rows_without_input: Option<usize>,
min_buffered_row: Option<usize>,
flush_threshold: usize,
partition_passthrough: PartitionPassthrough,
memory: MemoryReservation,
}
impl OutputBatchBuilder {
pub(in crate::execution::storage) fn needs_input_gather(&self) -> bool {
self.rows_without_input.is_none()
}
pub(in crate::execution::storage) fn needs_compact_classifier(&self) -> bool {
self.class_builder.is_some()
|| self.excluded_builder.is_some()
|| !self.classifier_bits_builders.is_empty()
}
pub(in crate::execution::storage) fn reserve_compact_rows(
&mut self,
rows: usize,
total_class_bytes: usize,
) -> Result<()> {
let before = self.class_bytes;
self.reserve_classifier_bytes_total(rows, total_class_bytes)?;
self.reserve_rows(rows, "compact matched rows")
.inspect_err(|_| self.rollback_class_bytes(before))
}
pub(in crate::execution::storage) fn compact_segment_work(
&self,
rows: usize,
) -> usize {
let columns = usize::from(self.needs_input_gather())
+ usize::from(self.class_builder.is_some())
+ usize::from(self.match_num_builder.is_some())
+ usize::from(self.seq_builder.is_some())
+ usize::from(self.excluded_builder.is_some())
+ self.classifier_bits_builders.len();
rows.saturating_mul(columns)
}
#[allow(clippy::too_many_arguments)]
pub(in crate::execution::storage) fn append_reserved_compact_segment(
&mut self,
rows: usize,
source_floor: usize,
classifier: Option<EncodedClassifier<'_>>,
match_number: i64,
first_sequence: i64,
excluded: bool,
) -> usize {
let work = self.compact_segment_work(rows);
if let Some(count) = &mut self.rows_without_input {
*count += rows;
} else {
let start = source_floor as u64;
let end = start + rows as u64;
self.row_refs.extend(
(start..end).map(|row| OutputRowRef::Input(AbsoluteRow::new(row))),
);
}
self.retain_source_floor(source_floor);
if let Some(builder) = &mut self.class_builder {
let classifier = classifier.expect("compact classifier metadata bound");
for _ in 0..rows {
builder.append_value(classifier.name);
}
}
if let Some(builder) = &mut self.match_num_builder {
builder.append_value_n(match_number, rows);
}
if let Some(builder) = &mut self.seq_builder {
for offset in 0..rows {
builder.append_value(first_sequence + offset as i64);
}
}
if let Some(builder) = &mut self.excluded_builder {
builder.append_n(rows, excluded);
}
for (builder, symbol) in self
.classifier_bits_builders
.iter_mut()
.zip(self.stream.classifier_bitset_symbol_ids().iter())
{
builder.append_n(
rows,
classifier.is_some_and(|value| value.symbol.to_index() == symbol.index()),
);
}
work
}
#[allow(clippy::too_many_arguments)]
pub(in crate::execution::storage) fn append_compact_rows(
&mut self,
rows: usize,
source_floor: usize,
classifier: Option<EncodedClassifier<'_>>,
match_number: i64,
first_sequence: i64,
excluded: bool,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<()> {
if self.rows_without_input.is_none() {
let end = source_floor.checked_add(rows).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE compact source end exceeds usize".into(),
)
})?;
let _ = absolute_row_from_usize(source_floor, "compact source start")?;
let _ = absolute_row_from_usize(end, "compact source end")?;
}
self.reserve_classified_rows(rows, classifier, "compact matched rows")?;
let work = self.append_reserved_compact_segment(
rows,
source_floor,
classifier,
match_number,
first_sequence,
excluded,
);
completed(work + 1)
}
pub(in crate::execution::storage) fn try_new(
stream: Arc<ExecutableRowStreamPlan>,
flush_threshold: usize,
partition_passthrough: PartitionPassthrough,
pending_row_capacity: usize,
memory: MemoryReservation,
) -> Result<Self> {
Self::try_new_inner(
stream,
SummaryOutputStorage::Ordinary,
flush_threshold,
partition_passthrough,
pending_row_capacity,
memory,
)
}
pub(in crate::execution::storage) fn try_new_direct_counts(
stream: Arc<ExecutableRowStreamPlan>,
summaries: Arc<[ExecutableDirectCountSummary]>,
automaton: Arc<crate::nfa::CompiledAutomaton>,
flush_threshold: usize,
partition_passthrough: PartitionPassthrough,
pending_row_capacity: usize,
mut memory: MemoryReservation,
) -> Result<Self> {
let mut columns = Vec::new();
try_reserve_accounted(
&mut columns,
&memory,
summaries.len(),
"count-summary columns",
)?;
let mut reductions = reduction::ReductionColumns::new(&summaries, &mut memory)?;
for summary in summaries.iter() {
if let Some(reductions) = &mut reductions {
let slot = summary
.reduction()
.map(|spec| reduction::ReductionColumn::new(spec, &memory))
.transpose()?;
reductions.slots.push(slot);
}
columns.push(DirectCountColumn {
values: Vec::new(),
memory: memory.new_empty(),
prepared_array: None,
});
}
Self::try_new_inner(
stream,
SummaryOutputStorage::DirectCounts {
automaton,
summaries,
columns,
reductions,
row_capacity: 0,
},
flush_threshold,
partition_passthrough,
pending_row_capacity,
memory,
)
}
fn try_new_inner(
stream: Arc<ExecutableRowStreamPlan>,
summary_output: SummaryOutputStorage,
flush_threshold: usize,
partition_passthrough: PartitionPassthrough,
pending_row_capacity: usize,
memory: MemoryReservation,
) -> Result<Self> {
let layout = &stream;
let mut row_refs = Vec::new();
let rows_without_input = stream
.spec()
.passthrough_input_indices()
.is_empty()
.then_some(0);
if rows_without_input.is_none() {
try_reserve_accounted(
&mut row_refs,
&memory,
pending_row_capacity,
"pending output row references",
)?;
}
let has_classifier = layout.has_classifier();
let has_match_number = layout.match_number_column().is_some();
let has_sequence_number = layout.has_sequence_number();
let has_excluded = layout.has_excluded();
let mut classifier_bits_builders = Vec::new();
classifier_bits_builders
.try_reserve(layout.classifier_bitset_symbol_ids().len())
.map_err(|error| {
DataFusionError::ResourcesExhausted(format!(
"MATCH_RECOGNIZE classifier metadata builders could not reserve {} entries: {error}",
layout.classifier_bitset_symbol_ids().len()
))
})?;
classifier_bits_builders.resize_with(
layout.classifier_bitset_symbol_ids().len(),
BooleanBuilder::new,
);
Ok(Self {
class_builder: has_classifier.then(StringBuilder::new),
class_bytes: 0,
class_reserved: 0,
match_num_builder: has_match_number.then(Int64Builder::new),
seq_builder: has_sequence_number.then(Int64Builder::new),
excluded_builder: has_excluded.then(BooleanBuilder::new),
classifier_bits_builders,
summary_output,
stream,
row_refs,
rows_without_input,
min_buffered_row: None,
flush_threshold,
partition_passthrough,
memory,
})
}
#[inline]
pub(in crate::execution::storage) fn len(&self) -> usize {
self.rows_without_input.unwrap_or(self.row_refs.len())
}
#[inline]
pub(in crate::execution::storage) fn is_empty(&self) -> bool {
self.len() == 0
}
pub(in crate::execution::storage) const fn min_buffered_row(&self) -> Option<usize> {
self.min_buffered_row
}
pub(in crate::execution::storage) fn reserve_row(
&mut self,
row: EncodedOutputRow<'_>,
) -> Result<()> {
self.reserve_classified_rows(1, row.classifier, row.reservation_context())
}
fn reserve_classifier_bytes(&mut self, rows: usize, value_len: usize) -> Result<()> {
if self.class_builder.is_none() {
return Ok(());
}
let Some(total_value_bytes) = rows.checked_mul(value_len) else {
return Err(DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE classifier string buffer exceeds i32 offset limit"
.into(),
));
};
self.reserve_classifier_bytes_total(rows, total_value_bytes)
}
fn reserve_classifier_bytes_total(
&mut self,
rows: usize,
total_value_bytes: usize,
) -> Result<()> {
if let Some(builder) = &self.class_builder {
if !builder
.values_slice()
.len()
.checked_add(total_value_bytes)
.is_some_and(|total| total <= i32::MAX as usize)
{
return Err(DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE classifier string buffer exceeds i32 offset limit"
.into(),
));
}
let bytes = rows
.checked_mul(size_of::<i32>())
.and_then(|offsets| offsets.checked_add(total_value_bytes))
.and_then(|bytes| bytes.checked_add(rows.div_ceil(8)))
.ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE classifier byte count overflow".into(),
)
})?;
let required = self.class_bytes.checked_add(bytes).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE classifier byte count overflow".into(),
)
})?;
if required > self.class_reserved {
let target = required
.checked_next_multiple_of(CLASSIFIER_RESERVATION_CHUNK)
.unwrap_or(required);
let delta = target - self.class_reserved;
match self.memory.try_grow(delta) {
Ok(()) => self.class_reserved = target,
Err(DataFusionError::ResourcesExhausted(_)) if target > required => {
self.memory.try_grow(required - self.class_reserved)?;
self.class_reserved = required;
}
Err(error) => return Err(error),
}
}
self.class_bytes = required;
}
Ok(())
}
pub(in crate::execution::storage) const fn class_bytes(&self) -> usize {
self.class_bytes
}
pub(in crate::execution::storage) fn rollback_class_bytes(&mut self, before: usize) {
self.class_bytes = before;
let _ = self.release_unused_classifier_bytes();
}
pub(super) fn release_unused_classifier_bytes(&mut self) -> Result<()> {
let excess = self.class_reserved.saturating_sub(self.class_bytes);
if excess != 0 {
self.memory.try_shrink(excess)?;
self.class_reserved -= excess;
}
Ok(())
}
fn reserve_classified_rows(
&mut self,
rows: usize,
classifier: Option<EncodedClassifier<'_>>,
context: &str,
) -> Result<()> {
let before = self.class_bytes;
self.reserve_classifier_bytes(rows, classifier.map_or(0, |c| c.name.len()))?;
self.reserve_rows(rows, context)
.inspect_err(|_| self.rollback_class_bytes(before))
}
fn reserve_rows(&mut self, additional: usize, context: &str) -> Result<()> {
if let Some(rows) = self.rows_without_input {
rows.checked_add(additional).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE pending output row count overflow".into(),
)
})?;
return Ok(());
}
if additional <= self.row_refs.capacity() - self.row_refs.len() {
return Ok(());
}
self.release_unused_classifier_bytes()?;
try_reserve_accounted(&mut self.row_refs, &self.memory, additional, context)
}
#[inline(always)]
pub(in crate::execution::storage) fn begin_reserved_row(
&mut self,
row: EncodedOutputRow<'_>,
) {
if let Some(rows) = &mut self.rows_without_input {
*rows += 1;
} else {
self.row_refs.push(row.row_ref);
}
self.retain_source_floor(row.source_floor);
if let Some(builder) = &mut self.class_builder {
if let Some(classifier) = row.classifier {
builder.append_value(classifier.name);
} else {
builder.append_null();
}
}
if let Some(builder) = &mut self.match_num_builder {
builder.append_value(row.match_number);
}
if let Some(builder) = &mut self.seq_builder {
builder.append_value(row.sequence_number);
}
if let Some(builder) = &mut self.excluded_builder {
builder.append_value(row.excluded);
}
}
pub(in crate::execution::storage) fn reserve_summary(
&mut self,
count: usize,
) -> Result<()> {
if matches!(
&self.summary_output,
SummaryOutputStorage::DirectCounts {
reductions: None,
..
}
) {
self.reserve_direct_columns(count)?;
} else {
for index in 0..count {
self.reserve_summary_value(index)?;
}
}
Ok(())
}
pub(in crate::execution::storage) fn append_summary(
&mut self,
values: &mut [u64],
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<()> {
let mut work = CoarseWorkBatch::new(completed);
for (index, value) in values.iter_mut().enumerate() {
self.append_reserved_summary_value(index, std::mem::take(value));
work.complete_one()?;
}
work.finish()
}
fn reserve_direct_columns(
&mut self,
count: usize,
) -> Result<&mut [DirectCountColumn]> {
let SummaryOutputStorage::DirectCounts {
columns,
row_capacity,
..
} = &mut self.summary_output
else {
return internal_err!(
"MATCH_RECOGNIZE direct count-summary row requires direct-count output storage"
);
};
if count != columns.len() {
return internal_err!(
"MATCH_RECOGNIZE count-summary row has {} values, expected {}",
count,
columns.len()
);
}
if columns
.first()
.is_some_and(|column| column.values.len() >= *row_capacity)
{
let mut capacity = usize::MAX;
for column in columns.iter_mut() {
try_reserve_accounted(
&mut column.values,
&column.memory,
1,
"count-summary values",
)?;
capacity = capacity.min(column.values.capacity());
}
*row_capacity = capacity;
}
Ok(columns)
}
pub(in crate::execution::storage) fn retain_source_floor(
&mut self,
source_floor: usize,
) {
self.min_buffered_row = Some(
self.min_buffered_row
.map_or(source_floor, |row| row.min(source_floor)),
);
}
pub(in crate::execution::storage) fn append_classifier_fields(
&mut self,
classifier: Option<usize>,
work: &mut CoarseWorkBatch<'_>,
) -> Result<()> {
for (builder, symbol) in self
.classifier_bits_builders
.iter_mut()
.zip(self.stream.classifier_bitset_symbol_ids().iter())
{
builder.append_value(classifier == Some(symbol.index()));
work.complete_one()?;
}
Ok(())
}
#[cfg(test)]
pub(in crate::execution::storage) fn append_reserved_row(
&mut self,
row: EncodedOutputRow<'_>,
work: &mut CoarseWorkBatch<'_>,
) -> Result<()> {
self.begin_reserved_row(row);
self.append_classifier_fields(
row.classifier_symbol().map(|symbol| symbol.to_index()),
work,
)
}
#[inline]
pub(in crate::execution::storage) fn batch_size(&self) -> usize {
self.flush_threshold.max(1)
}
#[inline]
pub(in crate::execution::storage) fn rows_until_flush(&self) -> usize {
self.flush_threshold.saturating_sub(self.len()).max(1)
}
pub(in crate::execution::storage) fn append_unmatched_prefix_chunk(
&mut self,
end: usize,
row_presence: &mut RowPresence,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<bool> {
if !matches!(self.summary_output, SummaryOutputStorage::Ordinary) {
return internal_err!(
"MATCH_RECOGNIZE native selected-summary output cannot append unmatched rows"
);
}
let start = absolute_row_to_usize(
row_presence.first_unfinalized_row(),
"row-presence finalization start",
)?;
if start >= end {
return Ok(true);
}
let max_unmatched = self.rows_until_flush();
let scan_limit = self.batch_size().max(COARSE_WORK_BATCH_SIZE);
let scan_end = start.saturating_add(scan_limit).min(end);
let before_len = self.len();
let before_min_row = self.min_buffered_row;
let class_before = self.class_bytes;
let mut chunk_end = start;
let mut unmatched_count = 0usize;
let mut first_unmatched: Option<usize> = None;
let prepared = (|| -> Result<()> {
let mut work = CoarseWorkBatch::new(&mut *completed);
for index in start..scan_end {
let row = absolute_row_from_usize(index, "unmatched output row")?;
if !row_presence.contains(row) {
if first_unmatched.is_none() {
first_unmatched = Some(index);
}
if self.rows_without_input.is_none() {
self.reserve_classified_rows(
1,
None,
"unmatched output row references",
)?;
self.row_refs.push(OutputRowRef::Input(row));
}
unmatched_count += 1;
}
chunk_end = index + 1;
work.complete_one()?;
if unmatched_count == max_unmatched {
break;
}
}
work.finish()?;
if unmatched_count != 0 && self.rows_without_input.is_some() {
self.reserve_classified_rows(
unmatched_count,
None,
"unmatched output rows",
)?;
}
let trimmed_end =
absolute_row_from_usize(chunk_end, "row-presence finalization boundary")?;
row_presence.trim_prefix_with_work(trimmed_end, &mut *completed)?;
Ok(())
})();
if let Err(error) = prepared {
self.row_refs.truncate(before_len);
self.min_buffered_row = before_min_row;
self.rollback_class_bytes(class_before);
return Err(error);
}
if unmatched_count != 0 {
if let Some(rows) = &mut self.rows_without_input {
*rows += unmatched_count;
}
if let Some(floor) = first_unmatched {
self.retain_source_floor(floor);
}
if let Some(builder) = &mut self.class_builder {
builder.append_nulls(unmatched_count);
}
if let Some(builder) = &mut self.match_num_builder {
builder.append_nulls(unmatched_count);
}
if let Some(builder) = &mut self.seq_builder {
builder.append_nulls(unmatched_count);
}
if let Some(builder) = &mut self.excluded_builder {
builder.append_n(unmatched_count, false);
}
for builder in &mut self.classifier_bits_builders {
builder.append_n(unmatched_count, false);
}
}
Ok(chunk_end >= end)
}
#[inline]
pub(in crate::execution::storage) fn maybe_flush_with_work(
&mut self,
batches: &BatchCollection,
global_offset: usize,
history: Option<&SharedHistoryBuffer>,
pending_output: &mut PendingOutput,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<()> {
if self.len() >= self.flush_threshold {
pending_output.try_reserve(1).map_err(|error| {
DataFusionError::ResourcesExhausted(format!(
"MATCH_RECOGNIZE threshold output could not reserve one staged batch slot: {error}"
))
})?;
if let Some(batch) =
self.flush_collection(batches, global_offset, history, completed)?
{
pending_output.push_back(batch)?;
}
}
Ok(())
}
#[cfg(test)]
pub(in crate::execution::storage) fn validate_pending_metadata_len(
&self,
expected: usize,
) -> Result<()> {
self.validate_pending_output(expected, true, &mut |_| Ok(()))
}
fn validate_pending_output(
&self,
expected: usize,
validate_mixed: bool,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<()> {
let validate = |name: &str, index: Option<usize>, actual: usize| {
if actual == expected {
Ok(())
} else {
let name = match index {
Some(index) => format!("{name} {index}"),
None => name.to_owned(),
};
Err(DataFusionError::Internal(format!(
"MATCH_RECOGNIZE pending output builder {name} has {actual} rows but row descriptors have {expected}"
)))
}
};
if let Some(builder) = &self.class_builder {
validate("classifier", None, builder.len())?;
}
if let Some(builder) = &self.match_num_builder {
validate("match number", None, builder.len())?;
}
if let Some(builder) = &self.seq_builder {
validate("match sequence number", None, builder.len())?;
}
if let Some(builder) = &self.excluded_builder {
validate("excluded", None, builder.len())?;
}
for (index, builder) in self.classifier_bits_builders.iter().enumerate() {
validate("classifier bit", Some(index), builder.len())?;
}
let summary_fields = match &self.summary_output {
SummaryOutputStorage::DirectCounts {
reductions: Some(_),
..
} if !validate_mixed => 0,
SummaryOutputStorage::Ordinary => 0,
SummaryOutputStorage::DirectCounts {
columns,
reductions,
..
} => {
for (index, column) in columns.iter().enumerate() {
if let Some(slot) =
reductions.as_ref().and_then(|r| r.slots[index].as_ref())
{
let rows = match &column.prepared_array {
Some((array, _)) => array.len(),
None => slot.len(),
};
validate("selected reduction", Some(index), rows)?;
continue;
}
validate("count summary", Some(index), column.values.len())?;
}
columns.len()
}
};
completed(4 + self.classifier_bits_builders.len() + summary_fields)
}
#[cfg(test)]
pub(in crate::execution::storage) fn validate_no_pending_builder_tail(
&self,
) -> Result<()> {
if !self.is_empty() || self.min_buffered_row.is_some() {
return internal_err!(
"MATCH_RECOGNIZE selected-match failure retained a pending row"
);
}
self.validate_pending_metadata_len(0)
}
#[cfg(test)]
pub(in crate::execution::storage) fn inject_pending_input(
&mut self,
row: AbsoluteRow,
source_floor: usize,
match_number: i64,
) {
self.reserve_rows(1, "test output row").unwrap();
if let Some(rows) = &mut self.rows_without_input {
*rows += 1;
} else {
self.row_refs.push(OutputRowRef::Input(row));
}
self.min_buffered_row = Some(source_floor);
if let Some(builder) = &mut self.match_num_builder {
builder.append_value(match_number);
}
}
#[cfg(test)]
pub(in crate::execution::storage) fn set_min_buffered_row(
&mut self,
row: Option<usize>,
) {
self.min_buffered_row = row;
}
fn empty_passthrough_batch(&self, num_rows: usize) -> Result<RecordBatch> {
Ok(RecordBatch::try_new_with_options(
Arc::clone(self.stream.passthrough_schema()),
vec![],
&datafusion::arrow::record_batch::RecordBatchOptions::new()
.with_row_count(Some(num_rows)),
)?)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::{
EmptyMatchesMode, MatchRecognizeOutputSpec, MatchSummaryField, NormalizedPattern,
Pattern, RowsPerMatch, Symbol, SymbolId,
};
use crate::execution::common::memory::new_unbounded_state_memory;
use crate::execution::matching::path::Sym;
use crate::execution::matching::{
ExecutableDirectCountSummary, ExecutableOutputFinalizer, ExecutableOutputPlan,
};
use crate::nfa::CompiledAutomaton;
use datafusion::arrow::array::{
Array, BooleanArray, Int32Array, Int64Array, StringArray,
};
use datafusion::arrow::datatypes::{DataType, Field};
pub(super) fn test_case(
metadata_columns: Vec<MatchMetadataColumn>,
classifier: bool,
) -> (OutputBatchBuilder, BatchCollection) {
test_case_with_inputs(vec![0], metadata_columns, classifier)
}
fn test_case_with_inputs(
input_columns: Vec<usize>,
metadata_columns: Vec<MatchMetadataColumn>,
classifier: bool,
) -> (OutputBatchBuilder, BatchCollection) {
let schema = Arc::new(Schema::new(vec![
Field::new("id", DataType::Int32, false),
Field::new(crate::core::symbol_col_name("A"), DataType::Boolean, false),
]));
let batch = RecordBatch::try_new(
Arc::clone(&schema),
vec![
Arc::new(Int32Array::from(vec![10, 20, 30])),
Arc::new(BooleanArray::from(vec![true, false, false])),
],
)
.unwrap();
let batches = BatchCollection::try_new(vec![batch], Arc::clone(&schema)).unwrap();
let pattern = NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named("A".into())));
let compiled = CompiledAutomaton::compile(&pattern, &["A".into()]).unwrap();
let spec = MatchRecognizeOutputSpec::new(
input_columns,
metadata_columns,
if classifier {
vec!["A".into()]
} else {
Vec::new()
},
);
let a = SymbolId::try_new(1, compiled.num_symbols()).expect("valid A slot");
let classifier_ids = classifier.then_some(a).into_iter().collect::<Arc<[_]>>();
let resolved = ExecutableOutputPlan::try_rows(
schema.as_ref(),
spec,
classifier_ids,
RowsPerMatch::AllRows(EmptyMatchesMode::Show),
&compiled,
)
.unwrap();
let builder = OutputBatchBuilder::try_new(
Arc::clone(resolved.stream()),
16,
PartitionPassthrough::default(),
17,
new_unbounded_state_memory().new_empty(),
)
.unwrap();
(builder, batches)
}
fn representative(row: usize) -> EncodedOutputRow<'static> {
EncodedOutputRow {
row_ref: OutputRowRef::Input(AbsoluteRow::new(row as u64)),
source_floor: row,
classifier: None,
match_number: 1,
sequence_number: 1,
excluded: false,
matched_physical_row: Some(AbsoluteRow::new(row as u64)),
}
}
fn admit_summary_representative(
builder: &mut OutputBatchBuilder,
row: EncodedOutputRow<'_>,
) {
builder.reserve_row(row).unwrap();
builder.begin_reserved_row(row);
}
#[test]
fn outputs_without_input_columns_keep_cardinality_and_unmatched_metadata() {
use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
use datafusion_execution::memory_pool::{
GreedyMemoryPool, MemoryConsumer, MemoryPool,
};
for metadata in [vec![], vec![MatchMetadataColumn::MatchNumber]] {
let (mut builder, batches) =
test_case_with_inputs(vec![], metadata.clone(), false);
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1 << 20));
builder.memory =
MemoryConsumer::new("unmatched-cardinality-test").register(&pool);
let chunk_size = builder.batch_size().max(COARSE_WORK_BATCH_SIZE);
let batch = batches.batch(0);
let batches = BatchCollection::try_new(
vec![batch.clone(); chunk_size / batch.num_rows() + 2],
Arc::clone(batches.schema()),
)
.unwrap();
let rows = batches.num_rows();
let mut presence = RowPresence::try_new_unbounded().unwrap();
for index in [0, chunk_size] {
let row = representative(index);
builder.reserve_row(row).unwrap();
builder.begin_reserved_row(row);
presence.mark(AbsoluteRow::new(index as u64)).unwrap();
}
assert_eq!(builder.len(), 2);
assert_eq!(builder.row_refs.capacity(), 0);
let mut scanned = 0;
let mut outputs = Vec::new();
loop {
let mut work = 0;
let finished = builder
.append_unmatched_prefix_chunk(rows, &mut presence, &mut |units| {
work += units;
Ok(())
})
.unwrap();
assert!(work > 0);
scanned += work;
assert!(builder.len() <= builder.batch_size());
assert_eq!(pool.reserved(), 0, "unmatched rows only need a count");
if (builder.len() >= builder.batch_size() || finished)
&& let Some(batch) = builder
.flush_collection(&batches, 0, None, &mut |_| Ok(()))
.unwrap()
{
assert!(batch.num_rows() <= builder.batch_size());
assert_eq!(batch.num_columns(), metadata.len());
outputs.push(batch);
}
if finished {
break;
}
}
assert_eq!(scanned, rows);
assert_eq!(
presence.first_unfinalized_row(),
AbsoluteRow::new(rows as u64)
);
assert!(
outputs.len() > 1,
"unmatched rows must flush in <= flush_threshold batches"
);
let output = datafusion::arrow::compute::concat_batches(
builder.stream.schema(),
&outputs,
)
.unwrap();
assert_eq!(output.num_rows(), rows);
assert_eq!(output.num_columns(), metadata.len());
if !metadata.is_empty() {
let mut expected = vec![None; rows];
expected[..2].fill(Some(1));
assert_eq!(output.column(0).as_ref(), &Int64Array::from(expected));
}
builder.validate_no_pending_builder_tail().unwrap();
}
}
#[test]
fn representative_optional_builder_subsets_stay_aligned_after_each_append() {
let optional_metadata = [
MatchMetadataColumn::Classifier,
MatchMetadataColumn::MatchNumber,
MatchMetadataColumn::MatchSequenceNumber,
MatchMetadataColumn::Excluded,
];
for (mask, classifier_bits) in [
(0, false),
(15, true),
(1, false),
(2, false),
(4, false),
(8, false),
(0, true),
(9, true),
] {
let metadata_columns = optional_metadata
.iter()
.enumerate()
.filter_map(|(index, column)| {
(mask & (1 << index) != 0).then_some(*column)
})
.collect::<Vec<_>>();
let (mut builder, batches) =
test_case(metadata_columns.clone(), classifier_bits);
let classifier = EncodedClassifier {
symbol: Sym::from_index(1),
name: "A",
};
let rows = [
EncodedOutputRow {
row_ref: OutputRowRef::Input(AbsoluteRow::new(0)),
source_floor: 0,
classifier: Some(classifier),
match_number: 7,
sequence_number: 1,
excluded: true,
matched_physical_row: Some(AbsoluteRow::new(0)),
},
EncodedOutputRow {
row_ref: OutputRowRef::Input(AbsoluteRow::new(1)),
source_floor: 1,
classifier: None,
match_number: 7,
sequence_number: 2,
excluded: true,
matched_physical_row: Some(AbsoluteRow::new(1)),
},
EncodedOutputRow {
row_ref: OutputRowRef::Input(AbsoluteRow::new(2)),
source_floor: 2,
classifier: None,
match_number: 7,
sequence_number: -1,
excluded: false,
matched_physical_row: None,
},
EncodedOutputRow {
row_ref: OutputRowRef::Virtual,
source_floor: 0,
classifier: None,
match_number: 8,
sequence_number: 1,
excluded: false,
matched_physical_row: None,
},
];
for (index, row) in rows.into_iter().enumerate() {
builder.reserve_row(row).unwrap();
let mut completed = |_| Ok(());
let mut work = CoarseWorkBatch::new(&mut completed);
builder.append_reserved_row(row, &mut work).unwrap();
work.finish().unwrap();
builder.validate_pending_metadata_len(index + 1).unwrap();
}
let output = builder
.flush_collection(&batches, 0, None, &mut |_| Ok(()))
.unwrap()
.unwrap();
assert_eq!(output.num_rows(), 4);
assert_eq!(
output.column(0).as_ref(),
&Int32Array::from(vec![Some(10), Some(20), Some(30), None])
);
let expected: Vec<(MatchMetadataColumn, ArrayRef)> = vec![
(
MatchMetadataColumn::Classifier,
Arc::new(StringArray::from(vec![Some("A"), None, None, None])),
),
(
MatchMetadataColumn::MatchNumber,
Arc::new(Int64Array::from(vec![7, 7, 7, 8])),
),
(
MatchMetadataColumn::MatchSequenceNumber,
Arc::new(Int64Array::from(vec![1, 2, -1, 1])),
),
(
MatchMetadataColumn::Excluded,
Arc::new(BooleanArray::from(vec![true, true, false, false])),
),
];
for (column, values) in expected {
if metadata_columns.contains(&column) {
assert_eq!(
output.column_by_name(column.as_ref()).unwrap().as_ref(),
values.as_ref()
);
}
}
if classifier_bits {
assert_eq!(
output.column(output.num_columns() - 1).as_ref(),
&BooleanArray::from(vec![true, false, false, false])
);
}
}
}
#[test]
fn direct_count_values_are_admitted_before_append_and_reused_by_arrow() -> Result<()>
{
use datafusion_execution::memory_pool::{
GreedyMemoryPool, MemoryConsumer, MemoryPool,
};
const LIMIT: usize = 4096;
const WIDTH: usize = 2;
let schema = Arc::new(Schema::empty());
let batches = BatchCollection::try_new(vec![], Arc::clone(&schema))?;
let pattern = NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named("A".into())));
let compiled = Arc::new(CompiledAutomaton::compile(&pattern, &["A".into()])?);
let summaries = (0..WIDTH)
.map(|index| {
ExecutableDirectCountSummary::new(
MatchSummaryField::new(
index,
Arc::new(Field::new("count", DataType::Int64, false)),
),
None,
)
})
.collect();
let resolved = ExecutableOutputPlan::try_direct_counts(
&schema,
MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
Arc::from([]),
summaries,
&compiled,
)?;
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(LIMIT));
let memory = MemoryConsumer::new("direct-count-output-test").register(&pool);
let blocker = memory.new_empty();
let mut completed = |_| Ok(());
for deny in [true, false] {
let ExecutableOutputFinalizer::DirectCounts { summaries } =
resolved.finalizer()
else {
unreachable!()
};
let mut builder = OutputBatchBuilder::try_new_direct_counts(
Arc::clone(resolved.stream()),
Arc::clone(summaries),
Arc::clone(&compiled),
1024,
PartitionPassthrough::default(),
1025,
memory.new_empty(),
)?;
let baseline = pool.reserved();
assert_eq!(baseline, WIDTH * size_of::<DirectCountColumn>());
admit_summary_representative(&mut builder, representative(0));
let mut counts = [42, 7];
if deny {
blocker.try_grow(LIMIT - baseline - size_of::<i64>())?;
}
let append = builder
.reserve_summary(counts.len())
.and_then(|()| builder.append_summary(&mut counts, &mut |_| Ok(())));
let SummaryOutputStorage::DirectCounts { columns, .. } =
&builder.summary_output
else {
unreachable!();
};
if deny {
assert!(matches!(
append,
Err(DataFusionError::ResourcesExhausted(_))
));
assert_eq!(counts, [42, 7]);
assert!(columns.iter().all(|column| column.values.is_empty()));
assert_eq!(pool.reserved(), LIMIT);
} else {
append?;
assert_eq!(pool.reserved(), baseline + WIDTH * size_of::<i64>());
let value_buffers = columns
.iter()
.map(|column| column.values.as_ptr())
.collect::<Vec<_>>();
let assembly_bytes =
WIDTH * (size_of::<ArrayRef>() + size_of::<Int64Array>());
blocker.try_grow(LIMIT - pool.reserved() - assembly_bytes)?;
let batch = builder
.flush_collection(&batches, 0, None, &mut completed)?
.unwrap();
assert_eq!(batch.num_rows(), 1);
for ((column, value), buffer) in
batch.columns().iter().zip([42, 7]).zip(value_buffers)
{
let array = column.as_any().downcast_ref::<Int64Array>().unwrap();
assert_eq!(array.value(0), value);
assert_eq!(array.values().as_ptr(), buffer.cast());
}
assert_eq!(pool.reserved(), baseline + blocker.size());
}
drop(builder);
assert_eq!(pool.reserved(), blocker.size());
blocker.free();
assert_eq!(pool.reserved(), 0);
}
Ok(())
}
#[test]
fn visible_row_reference_reservation_tracks_growth_until_discard() {
use datafusion_execution::memory_pool::{
GreedyMemoryPool, MemoryConsumer, MemoryPool,
};
let (ordinary, batches) = test_case(vec![], false);
let stream = Arc::clone(&ordinary.stream);
drop(ordinary);
const LIMIT: usize = 4096;
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(LIMIT));
let reservation =
MemoryConsumer::new("visible-output-row-refs-test").register(&pool);
let blocker = reservation.new_empty();
blocker.try_grow(LIMIT).unwrap();
let mut builder = OutputBatchBuilder::try_new(
stream,
16,
PartitionPassthrough::default(),
0,
reservation,
)
.unwrap();
let row = representative(0);
let error = builder.reserve_row(row).unwrap_err();
assert!(matches!(error, DataFusionError::ResourcesExhausted(_)));
assert!(builder.is_empty());
assert_eq!(builder.row_refs.capacity(), 0);
assert_eq!(pool.reserved(), LIMIT);
drop(blocker);
assert_eq!(pool.reserved(), 0);
builder.reserve_row(row).unwrap();
let retained = builder.row_refs.capacity() * size_of::<OutputRowRef>();
assert!(retained > 0);
assert_eq!(pool.reserved(), retained);
let mut completed = |_| Ok(());
let mut work = CoarseWorkBatch::new(&mut completed);
builder.append_reserved_row(row, &mut work).unwrap();
work.finish().unwrap();
builder
.flush_collection(&batches, 0, None, &mut |_| Ok(()))
.unwrap()
.unwrap();
assert_eq!(pool.reserved(), retained);
drop(builder);
assert_eq!(pool.reserved(), 0);
}
#[test]
fn contiguous_flush_copies_when_final_assembly_exceeds_the_pool() {
use datafusion_execution::memory_pool::{
GreedyMemoryPool, MemoryConsumer, MemoryPool,
};
let mut metadata = Int64Builder::new();
metadata.append_slice(&[1, 1]);
let metadata_bytes = metadata.finish().get_array_memory_size();
let input_column_slot = size_of::<ArrayRef>();
assert!(metadata_bytes > input_column_slot);
for (headroom, copies_input) in [
(0, true),
(3 * input_column_slot + metadata_bytes, true),
(1 << 20, false),
] {
let (mut builder, test_case_batches) = test_case(
vec![
MatchMetadataColumn::MatchNumber,
MatchMetadataColumn::MatchSequenceNumber,
],
false,
);
let schema = Arc::clone(test_case_batches.schema());
let input = Arc::new(Int32Array::from_iter_values(0..8192));
let slice_bytes = input.slice(1, 2).get_array_memory_size();
let input_slice = input.values().as_ptr().wrapping_add(1);
let flag = Arc::new(BooleanArray::from(vec![true; input.len()]));
let batch =
RecordBatch::try_new(Arc::clone(&schema), vec![input, flag]).unwrap();
let batches = BatchCollection::try_new(vec![batch], schema).unwrap();
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(
slice_bytes + input_column_slot + headroom,
));
builder.memory =
MemoryConsumer::new("flush-slice-copy-fallback").register(&pool);
for (index, sequence) in [(1, 7), (2, 8)] {
let mut row = representative(index);
row.sequence_number = sequence;
builder.reserve_row(row).unwrap();
builder.begin_reserved_row(row);
}
let output = builder
.flush_collection(&batches, 0, None, &mut |_| Ok(()))
.unwrap()
.unwrap();
let values = output
.column(0)
.as_any()
.downcast_ref::<Int32Array>()
.unwrap();
assert_eq!(values.values().as_ref(), &[1, 2]);
assert_eq!(values.values().as_ptr() != input_slice, copies_input);
assert_eq!(output.column(1).as_ref(), &Int64Array::from(vec![1, 1]));
assert_eq!(output.column(2).as_ref(), &Int64Array::from(vec![7, 8]));
builder.validate_no_pending_builder_tail().unwrap();
assert_eq!(pool.reserved(), 0);
}
}
#[test]
fn failed_assembly_releases_temporary_columns() {
use datafusion_execution::memory_pool::{
GreedyMemoryPool, MemoryConsumer, MemoryPool,
};
for cancel in [false, true] {
let (mut builder, batches) = test_case(
vec![
MatchMetadataColumn::MatchNumber,
MatchMetadataColumn::Excluded,
],
false,
);
let limit = 1 << 20;
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(limit));
builder.memory = MemoryConsumer::new("assembly-discard-test").register(&pool);
let row = representative(0);
builder.reserve_row(row).unwrap();
let mut completed = |_| Ok(());
let mut work = CoarseWorkBatch::new(&mut completed);
builder.append_reserved_row(row, &mut work).unwrap();
work.finish().unwrap();
let columns = vec![batches.batch(0).column(0).slice(0, 1)];
let memory = builder.memory.new_empty();
memory
.try_grow(
columns[0].get_array_memory_size()
+ columns.capacity() * size_of::<ArrayRef>(),
)
.unwrap();
let data = gather::GatherBatch {
batch: RecordBatch::try_new(
Arc::clone(builder.stream.passthrough_schema()),
columns,
)
.unwrap(),
memory,
};
let occupied = MemoryConsumer::new("assembly-admission-test").register(&pool);
if !cancel {
occupied
.try_grow(limit - pool.reserved() - 3 * size_of::<ArrayRef>())
.unwrap();
}
let Err(error) = builder.finish_batch(
data,
1,
assembly::AssemblyInput::Gathered,
&mut |_| {
assert!(cancel);
internal_err!("cancelled output assembly")
},
) else {
panic!("assembly must fail");
};
if cancel {
assert!(error.to_string().contains("cancelled output assembly"));
} else {
assert!(matches!(error, DataFusionError::ResourcesExhausted(_)));
}
assert_eq!(builder.len(), 1);
assert_eq!(pool.reserved(), occupied.size());
drop(occupied);
drop(builder);
assert_eq!(pool.reserved(), 0);
}
}
#[test]
fn reserve_classifier_bytes_rejects_i32_offset_overflow_without_growing_memory() {
let (mut builder, _batches) =
test_case(vec![MatchMetadataColumn::Classifier], false);
builder
.class_builder
.as_mut()
.expect("classifier builder")
.append_value("abcd");
let before = builder.memory.size();
let err = builder
.reserve_classifier_bytes(1, i32::MAX as usize - 3)
.unwrap_err();
assert!(matches!(err, DataFusionError::ResourcesExhausted(_)));
assert!(
err.to_string()
.contains("classifier string buffer exceeds i32 offset limit")
);
assert_eq!(builder.memory.size(), before);
assert_eq!(builder.class_reserved, 0);
assert_eq!(builder.class_bytes, 0);
let err = builder.reserve_classifier_bytes(usize::MAX, 2).unwrap_err();
assert!(matches!(err, DataFusionError::ResourcesExhausted(_)));
assert!(
err.to_string()
.contains("classifier string buffer exceeds i32 offset limit")
);
assert_eq!(builder.memory.size(), before);
assert_eq!(builder.class_reserved, 0);
assert_eq!(builder.class_bytes, 0);
builder
.reserve_classifier_bytes(1, i32::MAX as usize - 4)
.unwrap();
assert!(builder.memory.size() > before);
assert!(builder.class_reserved > 0);
assert!(builder.class_bytes > 0);
}
#[test]
fn classifier_reservation_amortizes_credit_falls_back_in_tight_pool_and_releases_on_flush()
-> Result<()> {
use datafusion_execution::memory_pool::{
GreedyMemoryPool, MemoryConsumer, MemoryPool,
};
let (template, batches) = test_case(vec![MatchMetadataColumn::Classifier], false);
let stream = Arc::clone(&template.stream);
drop(template);
let generous_pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1 << 20));
let mut builder = OutputBatchBuilder::try_new(
Arc::clone(&stream),
16,
PartitionPassthrough::default(),
0,
MemoryConsumer::new("classifier-credit-reuse").register(&generous_pool),
)?;
builder.reserve_classifier_bytes(1, 3)?;
let single_row_bytes = 3 + size_of::<i32>() + 1;
assert_eq!(builder.class_bytes, single_row_bytes);
assert_eq!(builder.class_reserved, CLASSIFIER_RESERVATION_CHUNK);
assert_eq!(builder.memory.size(), CLASSIFIER_RESERVATION_CHUNK);
for step in 2..=16 {
builder.reserve_classifier_bytes(1, 3)?;
assert_eq!(builder.class_bytes, step * single_row_bytes);
assert_eq!(builder.class_reserved, CLASSIFIER_RESERVATION_CHUNK);
assert_eq!(builder.memory.size(), CLASSIFIER_RESERVATION_CHUNK);
}
drop(builder);
assert_eq!(generous_pool.reserved(), 0);
let tight_limit = 2 * single_row_bytes;
assert!(tight_limit < CLASSIFIER_RESERVATION_CHUNK);
let tight_pool: Arc<dyn MemoryPool> =
Arc::new(GreedyMemoryPool::new(tight_limit));
let mut tight_builder = OutputBatchBuilder::try_new(
Arc::clone(&stream),
16,
PartitionPassthrough::default(),
0,
MemoryConsumer::new("classifier-tight-pool").register(&tight_pool),
)?;
tight_builder.reserve_classifier_bytes(1, 3)?;
assert_eq!(tight_builder.class_bytes, single_row_bytes);
assert_eq!(tight_builder.class_reserved, single_row_bytes);
assert_eq!(tight_builder.memory.size(), single_row_bytes);
tight_builder.reserve_classifier_bytes(1, 3)?;
assert_eq!(tight_builder.class_bytes, 2 * single_row_bytes);
assert_eq!(tight_builder.class_reserved, 2 * single_row_bytes);
assert_eq!(tight_builder.memory.size(), 2 * single_row_bytes);
let err = tight_builder.reserve_classifier_bytes(1, 3).unwrap_err();
assert!(matches!(err, DataFusionError::ResourcesExhausted(_)));
assert_eq!(tight_builder.class_bytes, 2 * single_row_bytes);
assert_eq!(tight_builder.class_reserved, 2 * single_row_bytes);
assert_eq!(tight_builder.memory.size(), 2 * single_row_bytes);
drop(tight_builder);
assert_eq!(tight_pool.reserved(), 0);
let flush_pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1 << 20));
let mut flush_builder = OutputBatchBuilder::try_new(
stream,
16,
PartitionPassthrough::default(),
16,
MemoryConsumer::new("classifier-flush-release").register(&flush_pool),
)?;
let row_ref_bytes = flush_builder.memory.size();
let classifier = Some(EncodedClassifier {
symbol: Sym::from_index(1),
name: "A",
});
for index in 0..3 {
let mut row = representative(index);
row.classifier = classifier;
flush_builder.reserve_row(row)?;
flush_builder.begin_reserved_row(row);
}
assert!(flush_builder.class_bytes > 0);
assert_eq!(flush_builder.class_reserved, CLASSIFIER_RESERVATION_CHUNK);
assert_eq!(
flush_builder.memory.size(),
row_ref_bytes + CLASSIFIER_RESERVATION_CHUNK
);
let batch = flush_builder
.flush_collection(&batches, 0, None, &mut |_| Ok(()))?
.expect("flushed batch");
assert_eq!(batch.num_rows(), 3);
assert_eq!(flush_builder.class_bytes, 0);
assert_eq!(flush_builder.class_reserved, 0);
assert_eq!(flush_builder.memory.size(), row_ref_bytes);
assert_eq!(flush_pool.reserved(), row_ref_bytes);
drop(flush_builder);
assert_eq!(flush_pool.reserved(), 0);
Ok(())
}
}