use std::collections::HashMap;
use super::assembly::{AssemblyInput, BatchAssembly};
use super::*;
use crate::execution::common::memory::reserved_vec;
#[cfg(test)]
use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
use datafusion::arrow::array::{AsArray, PrimitiveArray, make_array};
use datafusion::arrow::buffer::{BooleanBuffer, Buffer, NullBuffer};
use datafusion::arrow::datatypes::{
ArrowPrimitiveType, DataType, Date32Type, Date64Type, Decimal128Type, Float32Type,
Float64Type, Int8Type, Int16Type, Int32Type, Int64Type, TimeUnit,
TimestampMicrosecondType, TimestampMillisecondType, TimestampNanosecondType,
TimestampSecondType, UInt8Type, UInt16Type, UInt32Type, UInt64Type,
};
use datafusion::common::ScalarValue;
use datafusion_hash_grouped_order::gather::{
canonical_interleave_type, compact_byte_view_array, interleave_compact_with_memory,
retype_gather_data,
};
pub(in crate::execution::storage) const VIRTUAL_DEFAULT_COORD: u64 = u64::MAX;
impl OutputBatchBuilder {
pub(in crate::execution::storage) fn flush_collection(
&mut self,
batches: &BatchCollection,
global_offset: usize,
history: Option<&SharedHistoryBuffer>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<Option<RecordBatch>> {
self.release_unused_classifier_bytes()?;
let output_len = self.len();
self.validate_pending_output(output_len, completed)?;
if output_len == 0 {
return Ok(None);
}
gather_edges(self, batches, global_offset, history, completed)?;
let source = self
.needs_input_gather()
.then(|| {
FlushSource::try_new(
batches,
global_offset,
history,
self.min_buffered_row,
)
})
.transpose()?;
let plan = source
.as_ref()
.map(|source| gather_plan(self, source, completed))
.transpose()?;
let mut source_slice = match (&source, &plan) {
(Some(source), Some(plan)) => contiguous_source(source, plan, completed)?,
_ => None,
};
let mut prepared_columns = None;
let output = loop {
let data = match (&source, &plan) {
(Some(source), Some(plan)) => {
gather_input(self, source, plan, &mut source_slice, completed)?
}
_ => GatherBatch {
batch: self.empty_passthrough_batch(output_len)?,
memory: self.memory.new_empty(),
},
};
let assembly = if let Some(columns) = prepared_columns.take() {
AssemblyInput::WithPreparedColumns(columns)
} else if source_slice.is_some() {
AssemblyInput::Sliced
} else {
AssemblyInput::Gathered
};
match self.finish_batch(data, output_len, assembly, completed)? {
BatchAssembly::Complete(output) => break output,
BatchAssembly::CopyInput(columns) => {
prepared_columns = columns;
source_slice = None;
}
}
};
self.row_refs.clear();
if let Some(rows) = &mut self.rows_without_input {
*rows = 0;
}
self.min_buffered_row = None;
Ok(Some(output))
}
}
struct EdgeCoordinates {
sources: GatherSources,
indices: Vec<(usize, usize)>,
memory: MemoryReservation,
}
fn gather_edges(
builder: &mut OutputBatchBuilder,
batches: &BatchCollection,
global_offset: usize,
history: Option<&SharedHistoryBuffer>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<()> {
let SummaryOutputStorage::DirectCounts {
summaries,
columns,
reductions,
automaton,
..
} = &mut builder.summary_output
else {
return Ok(());
};
let mut source = None;
for (index, (summary, column)) in summaries.iter().zip(columns.iter_mut()).enumerate()
{
if column.prepared_array.is_some() {
completed(1)?;
continue;
}
if let Some(Some(slot)) = reductions.as_mut().and_then(|r| r.slots.get_mut(index))
{
let reservation = builder.memory.new_empty();
let spec = summary.reduction().expect("bound reduction");
let array = slot.prepare_array(&spec.output_type, &reservation)?;
column.prepared_array = Some((array, reservation));
completed(1)?;
continue;
}
if summary.edge().is_none() {
completed(1)?;
}
if let Some(endpoint) = summary.metadata() {
column.prepared_array = Some(metadata::materialize(
endpoint,
&column.values,
automaton.id_to_symbol(),
&builder.memory,
completed,
)?);
continue;
}
let Some(edge) = summary.edge() else {
continue;
};
let input_index = edge.input_column;
let arrow_field = summary.field().arrow_field();
let field_type = arrow_field.data_type();
let default_value = edge.default_value.as_ref();
if source.is_none() {
source = Some(FlushSource::try_new(
batches,
global_offset,
builder.min_buffered_row.and(history),
builder.min_buffered_row,
)?);
}
let source = source.as_ref().expect("initialized edge source");
let single_current_batch =
source.history.is_none() && source.current.num_batches() == 1;
if single_current_batch
&& default_value.is_none()
&& let Some((array, memory)) = try_gather_single_batch_primitive_edge(
source.current.batch(0),
input_index,
field_type,
&column.values,
source.origin,
source.rows,
&builder.memory,
)?
{
let rows = column.values.len();
completed(rows.max(1))?;
column.prepared_array = Some((array, memory));
continue;
}
let mut coordinates = EdgeCoordinates {
sources: GatherSources::default(),
indices: Vec::new(),
memory: builder.memory.new_empty(),
};
let chunk = &column.values;
try_reserve_accounted(
&mut coordinates.indices,
&coordinates.memory,
chunk.len(),
"selected edge coordinates",
)?;
if single_current_batch {
let mut current_source_idx: Option<usize> = None;
for &position in chunk {
let (source_idx, row) = if position == 0 {
let idx = coordinates
.sources
.index(SourceBatch::Virtual, &coordinates.memory)?;
(idx, 0)
} else if position == VIRTUAL_DEFAULT_COORD {
let idx = coordinates
.sources
.index(SourceBatch::VirtualDefault, &coordinates.memory)?;
(idx, 0)
} else {
let absolute = absolute_row_to_usize(
AbsoluteRow::new(position - 1),
"selected edge",
)?;
let row = absolute.checked_sub(source.origin).ok_or_else(|| {
DataFusionError::Internal(
"MATCH_RECOGNIZE selected edge precedes retained input"
.into(),
)
})?;
if row >= source.rows {
return internal_err!(
"MATCH_RECOGNIZE collection row {row} is outside {} rows",
source.rows
);
}
let idx = match current_source_idx {
Some(idx) => idx,
None => {
let idx = coordinates
.sources
.index(SourceBatch::Current(0), &coordinates.memory)?;
current_source_idx = Some(idx);
idx
}
};
(idx, row)
};
coordinates.indices.push((source_idx, row));
}
} else {
for &position in chunk {
let (batch, row) = if position == 0 {
(SourceBatch::Virtual, 0)
} else if position == VIRTUAL_DEFAULT_COORD {
(SourceBatch::VirtualDefault, 0)
} else {
let absolute = absolute_row_to_usize(
AbsoluteRow::new(position - 1),
"selected edge",
)?;
let relative =
absolute.checked_sub(source.origin).ok_or_else(|| {
DataFusionError::Internal(
"MATCH_RECOGNIZE selected edge precedes retained input"
.into(),
)
})?;
source.locate(relative, completed)?
};
let index = coordinates.sources.index(batch, &coordinates.memory)?;
coordinates.indices.push((index, row));
}
}
completed(chunk.len())?;
let has_virtual = coordinates.sources.batches.contains(&SourceBatch::Virtual);
let default_scalar = if coordinates
.sources
.batches
.contains(&SourceBatch::VirtualDefault)
{
let Some(value) = default_value else {
return internal_err!(
"MATCH_RECOGNIZE virtual default edge coordinate has no default value"
);
};
Some(value)
} else {
None
};
let memory = builder.memory.new_empty();
let array = source.interleave_column(
input_index,
field_type,
has_virtual,
default_scalar,
&coordinates.sources.batches,
&coordinates.indices,
&memory,
)?;
completed(coordinates.sources.batches.len() + 1)?;
drop(coordinates);
memory.try_grow(array.get_array_memory_size())?;
column.prepared_array = Some((array, memory));
}
Ok(())
}
fn try_gather_single_batch_primitive_edge(
batch: &RecordBatch,
input_index: usize,
field_type: &DataType,
positions: &[u64],
origin: usize,
source_rows: usize,
memory: &MemoryReservation,
) -> Result<Option<(ArrayRef, MemoryReservation)>> {
let src_col = batch.columns().get(input_index).ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE gather is missing input column {input_index}"
))
})?;
if src_col.data_type() != field_type {
return Ok(None);
}
macro_rules! dispatch_primitive {
($ty:ty) => {
gather_primitive_edge_from_batch::<$ty>(
src_col.as_primitive::<$ty>(),
field_type,
positions,
origin,
source_rows,
memory,
)
.map(Some)
};
}
match field_type {
DataType::Int8 => dispatch_primitive!(Int8Type),
DataType::Int16 => dispatch_primitive!(Int16Type),
DataType::Int32 => dispatch_primitive!(Int32Type),
DataType::Int64 => dispatch_primitive!(Int64Type),
DataType::UInt8 => dispatch_primitive!(UInt8Type),
DataType::UInt16 => dispatch_primitive!(UInt16Type),
DataType::UInt32 => dispatch_primitive!(UInt32Type),
DataType::UInt64 => dispatch_primitive!(UInt64Type),
DataType::Float32 => dispatch_primitive!(Float32Type),
DataType::Float64 => dispatch_primitive!(Float64Type),
DataType::Decimal128(_, _) => dispatch_primitive!(Decimal128Type),
DataType::Date32 => dispatch_primitive!(Date32Type),
DataType::Date64 => dispatch_primitive!(Date64Type),
DataType::Timestamp(TimeUnit::Second, _) => {
dispatch_primitive!(TimestampSecondType)
}
DataType::Timestamp(TimeUnit::Millisecond, _) => {
dispatch_primitive!(TimestampMillisecondType)
}
DataType::Timestamp(TimeUnit::Microsecond, _) => {
dispatch_primitive!(TimestampMicrosecondType)
}
DataType::Timestamp(TimeUnit::Nanosecond, _) => {
dispatch_primitive!(TimestampNanosecondType)
}
_ => Ok(None),
}
}
#[inline]
fn resolve_single_batch_edge_row(
position: u64,
origin: usize,
source_rows: usize,
src_len: usize,
) -> Result<usize> {
if position == VIRTUAL_DEFAULT_COORD {
return internal_err!(
"MATCH_RECOGNIZE virtual default edge coordinate has no default value"
);
}
let absolute =
absolute_row_to_usize(AbsoluteRow::new(position - 1), "selected edge")?;
let row = absolute.checked_sub(origin).ok_or_else(|| {
DataFusionError::Internal(
"MATCH_RECOGNIZE selected edge precedes retained input".into(),
)
})?;
if row >= source_rows || row >= src_len {
return internal_err!(
"MATCH_RECOGNIZE collection row {row} is outside {source_rows} rows"
);
}
Ok(row)
}
fn gather_primitive_edge_from_batch<T: ArrowPrimitiveType>(
src: &PrimitiveArray<T>,
field_type: &DataType,
positions: &[u64],
origin: usize,
source_rows: usize,
memory: &MemoryReservation,
) -> Result<(ArrayRef, MemoryReservation)> {
let len = positions.len();
let arr_memory = memory.new_empty();
let mut values: Vec<T::Native> = Vec::new();
try_reserve_accounted(&mut values, &arr_memory, len, "selected edge values")?;
let mut validity: Option<Vec<u8>> = None;
let src_values = src.values().as_ref();
let src_len = src.len();
let mark_null = |idx: usize,
validity: &mut Option<Vec<u8>>,
arr_memory: &MemoryReservation|
-> Result<()> {
let bits = match validity {
Some(bits) => bits,
None => {
let byte_len = len.div_ceil(8);
let mut bits = Vec::new();
try_reserve_accounted(
&mut bits,
arr_memory,
byte_len,
"selected edge validity",
)?;
bits.resize(byte_len, 0xFF);
validity.insert(bits)
}
};
bits[idx >> 3] &= !(1u8 << (idx & 7));
Ok(())
};
if let Some(src_nulls) = src.nulls() {
for (idx, &position) in positions.iter().enumerate() {
if position == 0 {
mark_null(idx, &mut validity, &arr_memory)?;
values.push(T::default_value());
continue;
}
let row =
resolve_single_batch_edge_row(position, origin, source_rows, src_len)?;
if src_nulls.is_null(row) {
mark_null(idx, &mut validity, &arr_memory)?;
values.push(T::default_value());
} else {
values.push(src_values[row]);
}
}
} else {
for (idx, &position) in positions.iter().enumerate() {
if position == 0 {
mark_null(idx, &mut validity, &arr_memory)?;
values.push(T::default_value());
continue;
}
let row =
resolve_single_batch_edge_row(position, origin, source_rows, src_len)?;
values.push(src_values[row]);
}
}
let nulls = validity
.map(|bits| NullBuffer::new(BooleanBuffer::new(Buffer::from_vec(bits), 0, len)));
let array =
PrimitiveArray::<T>::new(values.into(), nulls).with_data_type(field_type.clone());
let array_bytes = array.get_array_memory_size();
if array_bytes > arr_memory.size() {
arr_memory.try_grow(array_bytes - arr_memory.size())?;
} else if array_bytes < arr_memory.size() {
arr_memory.shrink(arr_memory.size() - array_bytes);
}
Ok((Arc::new(array), arr_memory))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum SourceBatch {
Current(usize),
History(usize),
Virtual,
VirtualDefault,
}
struct FlushSource<'a> {
current: &'a BatchCollection,
current_origin: usize,
history: Option<&'a SharedHistoryBuffer>,
origin: usize,
rows: usize,
}
impl<'a> FlushSource<'a> {
fn try_new(
current: &'a BatchCollection,
current_origin: usize,
history: Option<&'a SharedHistoryBuffer>,
min_buffered_row: Option<usize>,
) -> Result<Self> {
let mut source = Self {
current,
current_origin,
history: None,
origin: current_origin,
rows: current.num_rows(),
};
let Some(history) = history else {
return Ok(source);
};
let origin = min_buffered_row
.ok_or_else(|| {
DataFusionError::Internal(
"MATCH_RECOGNIZE non-empty gather has no physical source floor"
.into(),
)
})?
.min(current_origin);
let end = history.end_index();
if origin > end {
return internal_err!(
"Required history starts at {origin}, after appended history end {end}"
);
}
if origin < history.head_index() {
return internal_err!(
"Required history row {origin} was already pruned; retained history starts at {}",
history.head_index()
);
}
if !current.is_empty() && current_origin > end {
return internal_err!(
"MATCH_RECOGNIZE retained history ends at absolute row {end}, leaving a gap before current input starts at {current_origin}"
);
}
if !current.is_empty() && origin == current_origin {
return Ok(source);
}
source.origin = origin;
source.history = Some(history);
source.rows = end - origin;
if !current.is_empty() && current_origin == end {
source.rows =
source.rows.checked_add(current.num_rows()).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE combined output source row count exceeds usize"
.into(),
)
})?;
}
Ok(source)
}
fn locate(
&self,
relative: usize,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<(SourceBatch, usize)> {
let absolute = self.origin.checked_add(relative).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE absolute gather row exceeds usize".into(),
)
})?;
if let Some(history) = self.history
&& absolute < history.end_index()
{
let (batch, row) = history.locate(absolute)?;
completed(1)?;
return Ok((SourceBatch::History(batch), row));
}
let relative = absolute.checked_sub(self.current_origin).ok_or_else(|| {
DataFusionError::Internal(
"MATCH_RECOGNIZE gather row precedes current input".into(),
)
})?;
let (batch, row) = self.current.locate_with_work(relative, completed)?;
Ok((SourceBatch::Current(batch), row))
}
fn batch(&self, batch: SourceBatch) -> Option<&'a RecordBatch> {
match batch {
SourceBatch::Current(index) => Some(self.current.batch(index)),
SourceBatch::History(index) => {
Some(self.history.expect("checked history source").batch(index))
}
SourceBatch::Virtual | SourceBatch::VirtualDefault => None,
}
}
}
#[derive(Default)]
struct GatherSources {
batches: Vec<SourceBatch>,
indices: HashMap<SourceBatch, usize>,
index_bytes: usize,
}
impl GatherSources {
fn index(
&mut self,
source: SourceBatch,
memory: &MemoryReservation,
) -> Result<usize> {
if self.batches.last() == Some(&source) {
return Ok(self.batches.len() - 1);
}
if self.batches.len() <= 32 {
if let Some(index) = self.batches.iter().position(|batch| *batch == source) {
return Ok(index);
}
} else {
if self.indices.is_empty() {
self.reserve_index(self.batches.len() + 1, memory)?;
for (index, &batch) in self.batches.iter().enumerate() {
self.indices.insert(batch, index);
}
}
if let Some(&index) = self.indices.get(&source) {
return Ok(index);
}
self.reserve_index(self.indices.len() + 1, memory)?;
}
let index = self.batches.len();
try_reserve_accounted(&mut self.batches, memory, 1, "gather input batches")?;
if !self.indices.is_empty() {
self.indices.insert(source, index);
}
self.batches.push(source);
Ok(index)
}
fn reserve_index(
&mut self,
required: usize,
memory: &MemoryReservation,
) -> Result<()> {
if required <= self.indices.capacity() {
return Ok(());
}
let bytes = required
.checked_next_power_of_two()
.and_then(|capacity| {
capacity.checked_mul(4 * size_of::<(SourceBatch, usize)>())
})
.ok_or_else(|| {
super::super::resource_error("gather source index size overflow".into())
})?;
memory.try_grow(bytes)?;
if let Err(error) = self.indices.try_reserve(required - self.indices.len()) {
memory.shrink(bytes);
return Err(super::super::resource_error(format!(
"gather source index allocation failed: {error}"
)));
}
memory.shrink(self.index_bytes);
self.index_bytes = bytes;
Ok(())
}
}
impl FlushSource<'_> {
#[allow(clippy::too_many_arguments)]
fn interleave_column(
&self,
input_index: usize,
target_type: &DataType,
has_virtual: bool,
default_value: Option<&ScalarValue>,
sources: &[SourceBatch],
indices: &[(usize, usize)],
memory: &MemoryReservation,
) -> Result<ArrayRef> {
let scratch_memory = memory.new_empty();
let canonical_type = canonical_interleave_type(target_type)?;
let nulls = has_virtual.then(|| new_null_array(&canonical_type, 1));
if let Some(nulls) = &nulls {
scratch_memory.try_grow(nulls.get_array_memory_size())?;
}
let defaults = default_value
.map(|value| value.to_array_of_size(1))
.transpose()?;
if let Some(defaults) = &defaults {
scratch_memory.try_grow(defaults.get_array_memory_size())?;
}
let mut arrays = Vec::new();
try_reserve_accounted(
&mut arrays,
&scratch_memory,
sources.len(),
"borrowed gather input arrays",
)?;
for &batch in sources {
let array = match batch {
SourceBatch::Current(_) | SourceBatch::History(_) => {
let batch = self.batch(batch).expect("physical source batch");
batch.columns().get(input_index).ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE gather is missing input column {input_index}"
))
})?
}
SourceBatch::Virtual => {
nulls.as_ref().expect("virtual gather has a typed NULL")
}
SourceBatch::VirtualDefault => defaults
.as_ref()
.expect("virtual default gather has a typed default"),
};
arrays.push(array.as_ref());
}
let needs_retype = arrays.iter().any(|a| a.data_type() != &canonical_type);
let mut normalized = reserved_vec(
if needs_retype { arrays.len() } else { 0 },
&scratch_memory,
"gather array headers",
)?;
if needs_retype {
for array in &arrays {
normalized.push(if array.data_type() == &canonical_type {
array.slice(0, array.len())
} else {
make_array(retype_gather_data(
array.to_data(),
&canonical_type,
false,
)?)
});
}
arrays.clear();
for array in &normalized {
arrays.push(array.as_ref());
}
}
let array = interleave_compact_with_memory(&arrays, indices, Some(memory))?;
if target_type != &canonical_type {
return Ok(make_array(retype_gather_data(
array.to_data(),
target_type,
false,
)?));
}
Ok(array)
}
}
pub(super) struct GatherBatch {
pub(super) batch: RecordBatch,
pub(super) memory: MemoryReservation,
}
struct GatherColumns {
sources: GatherSources,
indices: Vec<(usize, usize)>,
columns: Vec<ArrayRef>,
rows: usize,
payload_bytes: usize,
memory: MemoryReservation,
}
impl GatherColumns {
fn try_new(rows: usize, columns: usize, memory: MemoryReservation) -> Result<Self> {
let indices = reserved_vec(rows, &memory, "gather indices")?;
let columns = reserved_vec(columns, &memory, "gather columns")?;
Ok(Self {
sources: GatherSources::default(),
indices,
columns,
rows,
payload_bytes: 0,
memory,
})
}
fn push_column(&mut self, array: ArrayRef) -> Result<()> {
let bytes = array.get_array_memory_size();
let payload_bytes = self.payload_bytes.checked_add(bytes).ok_or_else(|| {
super::super::resource_error("gather column byte size overflow".into())
})?;
self.memory.try_grow(bytes)?;
self.columns.push(array);
self.payload_bytes = payload_bytes;
Ok(())
}
fn finish(mut self, builder: &OutputBatchBuilder) -> Result<GatherBatch> {
let columns = std::mem::take(&mut self.columns);
let retained_bytes = columns
.capacity()
.checked_mul(size_of::<ArrayRef>())
.and_then(|bytes| bytes.checked_add(self.payload_bytes))
.ok_or_else(|| {
super::super::resource_error("gather result size overflow".into())
})?;
let batch = RecordBatch::try_new_with_options(
Arc::clone(builder.stream.passthrough_schema()),
columns,
&datafusion::arrow::record_batch::RecordBatchOptions::new()
.with_row_count(Some(self.rows)),
)?;
Ok(GatherBatch {
batch,
memory: self.memory.split(retained_bytes),
})
}
}
fn gather_plan(
builder: &OutputBatchBuilder,
source: &FlushSource<'_>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<GatherPlan> {
let mut plan = GatherPlan::try_empty(
absolute_row_from_usize(source.origin, "output source origin")?,
source.rows,
)?;
for &row in &builder.row_refs {
plan.try_push(row)?;
}
completed(builder.row_refs.len())?;
Ok(plan)
}
fn contiguous_source(
source: &FlushSource<'_>,
plan: &GatherPlan,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<Option<(SourceBatch, usize)>> {
if let Some(start) = plan.contiguous_input_start() {
let first = source.locate(start, completed)?;
let last = source.locate(start + plan.len() - 1, completed)?;
return Ok((first.0 == last.0).then_some(first));
}
Ok(None)
}
fn gather_input(
builder: &OutputBatchBuilder,
source: &FlushSource<'_>,
plan: &GatherPlan,
source_slice: &mut Option<(SourceBatch, usize)>,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<GatherBatch> {
let columns = builder.stream.spec().passthrough_input_indices();
'copy_fallback: loop {
let mut gathered = GatherColumns::try_new(
if source_slice.is_some() {
0
} else {
plan.len()
},
columns.len(),
builder.memory.new_empty(),
)?;
gathered.rows = plan.len();
if source_slice.is_none() {
for &row_ref in &builder.row_refs {
let (batch, row) =
source.locate(plan.relative_input_row(row_ref)?, completed)?;
let ordinary = (gathered.sources.index(batch, &gathered.memory)?, row);
gathered.indices.push(ordinary);
}
completed(plan.len())?;
}
for &input_index in columns {
if let Some((batch, offset)) = *source_slice {
let array = source.batch(batch).expect("physical input slice")
.columns().get(input_index).ok_or_else(|| DataFusionError::Internal(
format!("MATCH_RECOGNIZE direct passthrough is missing input column {input_index}"),
))?;
let array = if offset == 0 && plan.len() == array.len() {
compact_byte_view_array(Arc::clone(array))
} else {
compact_byte_view_array(array.slice(offset, plan.len()))
};
match gathered.push_column(array) {
Ok(()) => {}
Err(DataFusionError::ResourcesExhausted(_)) => {
*source_slice = None;
completed(1)?;
continue 'copy_fallback;
}
Err(error) => return Err(error),
}
completed(1)?;
} else {
let target_type = source
.current
.schema()
.fields()
.get(input_index)
.ok_or_else(|| {
DataFusionError::Internal(format!(
"MATCH_RECOGNIZE gather is missing input column {input_index}"
))
})?
.data_type();
let result = source
.interleave_column(
input_index,
target_type,
false,
None,
&gathered.sources.batches,
&gathered.indices,
&gathered.memory,
)
.and_then(|array| gathered.push_column(array));
let accounting = completed(gathered.sources.batches.len() + 1);
result?;
accounting?;
}
}
let result = gathered.finish(builder)?;
completed(1)?;
return Ok(result);
}
}
#[cfg(test)]
mod builder_fast_path_tests;
#[cfg(test)]
mod tests {
use super::*;
use crate::core::{
MatchRecognizeOutputSpec, MatchSummaryField, NormalizedPattern, Pattern, Symbol,
};
use crate::execution::common::memory::new_unbounded_state_memory;
use crate::execution::matching::{ExecutableOutputFinalizer, ExecutableOutputPlan};
use crate::nfa::CompiledAutomaton;
use datafusion::arrow::array::Int64Array;
use datafusion::arrow::datatypes::Field;
#[test]
fn wide_count_only_direct_counts_flush_reports_work() -> Result<()> {
const WIDTH: usize = 2 * COARSE_WORK_BATCH_SIZE + 3;
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(format!("c{index}"), DataType::Int64, false)),
),
None,
)
})
.collect();
let plan = ExecutableOutputPlan::try_direct_counts(
&schema,
MatchRecognizeOutputSpec::new(vec![], vec![], vec![]),
Arc::from([]),
summaries,
&compiled,
)?;
let ExecutableOutputFinalizer::DirectCounts { summaries } = plan.finalizer()
else {
unreachable!()
};
let mut builder = OutputBatchBuilder::try_new_direct_counts(
Arc::clone(plan.stream()),
Arc::clone(summaries),
Arc::clone(&compiled),
16,
0,
new_unbounded_state_memory().new_empty(),
)?;
let mut noop = |_| Ok(());
let mut work = CoarseWorkBatch::new(&mut noop);
let mut counts: Vec<u64> = (1..=WIDTH as u64).collect();
builder.reserve_summary(counts.len())?;
builder.append_summary(&mut counts, work.reporter())?;
builder.append_compact_rows(1, 0, None, 1, 1, false, &mut |_| Ok(()))?;
work.finish()?;
let mut reported = 0;
let batch = builder
.flush_collection(&batches, 0, None, &mut |units| {
reported += units;
Ok(())
})?
.expect("one synchronous wide count batch");
assert_eq!(reported, 5 + 3 * WIDTH);
assert_eq!((batch.num_rows(), batch.num_columns()), (1, WIDTH));
for (index, column) in batch.columns().iter().enumerate() {
let values = column.as_any().downcast_ref::<Int64Array>().unwrap();
assert_eq!(values.value(0), (index + 1) as i64);
}
assert_eq!(builder.len(), 0);
Ok(())
}
#[test]
fn unmatched_staging_bounds_batches_and_rolls_back_on_error() -> Result<()> {
use crate::core::{EmptyMatchesMode, RowsPerMatch};
use datafusion::arrow::array::{AsArray, BooleanArray, Int32Array};
use datafusion::arrow::datatypes::{Int32Type, Int64Type};
use datafusion::execution::memory_pool::{
GreedyMemoryPool, MemoryConsumer, MemoryPool,
};
const ROWS: usize = COARSE_WORK_BATCH_SIZE + 18;
const FLUSH_THRESHOLD: usize = 40;
let schema = Arc::new(Schema::new(vec![
Field::new("v", 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_iter_values(1..=ROWS as i32)),
Arc::new(BooleanArray::from(vec![true; ROWS])),
],
)?;
let batches = BatchCollection::try_new(vec![batch], Arc::clone(&schema))?;
let pattern = NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named("A".into())));
let compiled = CompiledAutomaton::compile(&pattern, &["A".into()])?;
let plan = ExecutableOutputPlan::try_rows(
schema.as_ref(),
MatchRecognizeOutputSpec::new(
vec![0],
vec![
MatchMetadataColumn::MatchNumber,
MatchMetadataColumn::Classifier,
],
vec![],
),
Arc::from([]),
RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched),
&compiled,
)?;
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1 << 20));
let mut builder = OutputBatchBuilder::try_new(
Arc::clone(plan.stream()),
FLUSH_THRESHOLD,
0,
MemoryConsumer::new("unmatched-prefix-staging-test").register(&pool),
)?;
let mut presence = RowPresence::try_new(
MemoryConsumer::new("unmatched-prefix-staging-presence").register(&pool),
)?;
let classifier = Some(EncodedClassifier {
symbol: crate::execution::matching::path::Sym::from_index(1),
name: "A",
});
builder.append_compact_rows(2, 0, classifier, 1, 1, false, &mut |_| Ok(()))?;
presence.mark(AbsoluteRow::new(0))?;
presence.mark(AbsoluteRow::new(1))?;
let class_bytes_before = builder.class_bytes();
let mut calls = 0usize;
let err = builder
.append_unmatched_prefix_chunk(ROWS, &mut presence, &mut |_| {
calls += 1;
if calls == 1 {
internal_err!("injected mid-staging cancellation")
} else {
Ok(())
}
})
.unwrap_err();
assert!(
err.to_string()
.contains("injected mid-staging cancellation")
);
assert_eq!(builder.len(), 2);
assert_eq!(builder.class_bytes(), class_bytes_before);
assert_eq!(presence.first_unfinalized_row(), AbsoluteRow::new(0));
builder.validate_pending_metadata_len(2)?;
let mut chunks = 0usize;
let mut outputs = Vec::new();
loop {
let finished = builder.append_unmatched_prefix_chunk(
ROWS,
&mut presence,
&mut |_| Ok(()),
)?;
chunks += 1;
assert!(builder.len() <= FLUSH_THRESHOLD);
if (builder.len() >= builder.batch_size() || finished)
&& let Some(batch) =
builder.flush_collection(&batches, 0, None, &mut |_| Ok(()))?
{
assert!(batch.num_rows() <= FLUSH_THRESHOLD);
outputs.push(batch);
}
if finished {
break;
}
}
assert!(chunks >= 2, "staging must proceed in bounded chunks");
assert!(
outputs.len() >= 2,
"unmatched output must flush in <= flush_threshold batches"
);
assert_eq!(
presence.first_unfinalized_row(),
AbsoluteRow::new(ROWS as u64)
);
let output =
datafusion::arrow::compute::concat_batches(plan.stream().schema(), &outputs)?;
assert_eq!(output.num_rows(), ROWS);
let vals = output.column(0).as_primitive::<Int32Type>();
let mns = output.column(1).as_primitive::<Int64Type>();
let cls = output.column(2).as_string::<i32>();
assert_eq!((vals.value(0), mns.value(0), cls.value(0)), (1, 1, "A"));
assert_eq!((vals.value(1), mns.value(1), cls.value(1)), (2, 1, "A"));
for row in 2..ROWS {
assert_eq!(vals.value(row), (row + 1) as i32);
assert!(mns.is_null(row));
assert!(cls.is_null(row));
}
assert_eq!(builder.len(), 0);
drop((output, outputs));
drop(builder);
drop(presence);
assert_eq!(pool.reserved(), 0);
Ok(())
}
}
#[cfg(test)]
mod dictionary_tests {
use super::*;
use datafusion::arrow::array::{
DictionaryArray, Int8Array, StringViewArray, StructArray,
};
use datafusion::arrow::datatypes::Field;
use datafusion::execution::memory_pool::{
GreedyMemoryPool, MemoryConsumer, MemoryPool,
};
#[test]
fn output_gathers_selected_narrow_view_dictionaries() -> Result<()> {
for nested in [false, true] {
let columns: Vec<ArrayRef> = (0..2)
.map(|source| {
let values = StringViewArray::from_iter_values(
(0..120).map(|i| format!("value-{}", source * 120 + i)),
);
let dict: ArrayRef = Arc::new(
DictionaryArray::<Int8Type>::try_new(
Int8Array::from(vec![119]),
Arc::new(values),
)
.unwrap(),
);
if nested {
Arc::new(StructArray::new(
vec![Field::new("d", dict.data_type().clone(), false)].into(),
vec![dict],
None,
)) as ArrayRef
} else {
dict
}
})
.collect();
let schema = Arc::new(Schema::new(vec![Field::new(
"v",
columns[0].data_type().clone(),
false,
)]));
let batches = columns
.iter()
.map(|a| RecordBatch::try_new(Arc::clone(&schema), vec![Arc::clone(a)]))
.collect::<std::result::Result<Vec<_>, _>>()?;
let collection = BatchCollection::try_new(batches, Arc::clone(&schema))?;
let source = FlushSource::try_new(&collection, 0, None, None)?;
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(1 << 20));
let memory = MemoryConsumer::new("dictionary output").register(&pool);
let output = source.interleave_column(
0,
schema.field(0).data_type(),
false,
None,
&[SourceBatch::Current(0), SourceBatch::Current(1)],
&[(1, 0), (0, 0)],
&memory,
)?;
memory.try_grow(output.get_array_memory_size())?;
assert_eq!(output.data_type(), schema.field(0).data_type());
let dict = if nested {
output.as_struct().column(0).as_ref()
} else {
output.as_ref()
}
.as_dictionary::<Int8Type>();
assert_eq!(dict.values().len(), 2);
assert_eq!(
dict.values().as_string_view().value(dict.key(0).unwrap()),
"value-239"
);
assert_eq!(
dict.values().as_string_view().value(dict.key(1).unwrap()),
"value-119"
);
assert_eq!(pool.reserved(), output.get_array_memory_size());
drop(output);
drop(memory);
assert_eq!(pool.reserved(), 0);
}
Ok(())
}
}