use super::bound_columns::{BoundBatchColumns, BoundBatchRow};
use crate::execution::common::memory::{reserved_vec, try_reserve_accounted};
use crate::execution::common::progress::CoarseWorkBatch;
use crate::execution::storage::history_buffer::SharedHistoryBuffer;
use datafusion::arrow::array::ArrayRef;
use datafusion::arrow::datatypes::{FieldRef, Schema, SchemaRef};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion_common::heap_size::{DFHeapSize, DFHeapSizeCtx};
use datafusion_common::{DataFusionError, Result, internal_err};
use datafusion_execution::memory_pool::MemoryReservation;
use std::mem::size_of;
use std::ops::Range;
#[derive(Debug)]
pub struct BatchCollection {
bound: Vec<BoundBatchColumns>,
batches: Vec<RecordBatch>,
cumulative_rows: Vec<usize>,
schema: SchemaRef,
}
pub(in crate::execution) fn gather_size_overflow() -> DataFusionError {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE history gather memory size exceeds usize".into(),
)
}
pub(crate) fn gathered_schema_bytes(schema: &Schema) -> Result<usize> {
size_of::<Schema>()
.checked_add(4 * size_of::<usize>())
.and_then(|bytes| {
schema
.fields()
.len()
.checked_mul(size_of::<FieldRef>())
.and_then(|handles| bytes.checked_add(handles))
})
.and_then(|bytes| {
bytes.checked_add(schema.metadata().heap_size(&mut DFHeapSizeCtx::default()))
})
.ok_or_else(gather_size_overflow)
}
#[derive(Debug)]
pub(crate) struct PreparingReplayCollection {
collection: BatchCollection,
key_rows: Vec<crate::execution::matching::PartitionKeyRows>,
batches: Range<usize>,
batch_offset: usize,
last_batch_end: usize,
expected_rows: usize,
history_bounds: (usize, usize),
memory: MemoryReservation,
}
impl PreparingReplayCollection {
pub(crate) fn try_new(
history: &SharedHistoryBuffer,
start: usize,
end_exclusive: usize,
schema: SchemaRef,
memory: MemoryReservation,
) -> Result<Self> {
let mut collection = BatchCollection::empty(schema);
let expected_rows = end_exclusive.checked_sub(start).ok_or_else(|| {
DataFusionError::Internal(
"MATCH_RECOGNIZE history replay range has reversed bounds".into(),
)
})?;
let history_bounds = (history.head_index(), history.end_index());
if start < history_bounds.0 {
return internal_err!(
"Required history range {start}..{end_exclusive} was already pruned; retained history starts at {}",
history_bounds.0
);
}
if end_exclusive > history_bounds.1 {
return internal_err!(
"Required history range {start}..{end_exclusive} extends past appended history end {}",
history_bounds.1
);
}
if &collection.schema != history.schema() {
return internal_err!(
"MATCH_RECOGNIZE history replay schema differs from its source"
);
}
let (batches, batch_offset, last_batch_end) = if expected_rows == 0 {
(0..0, 0, 0)
} else {
let (first, offset) = history.locate(start)?;
let (last, last_offset) = history.locate(end_exclusive - 1)?;
(first..last + 1, offset, last_offset + 1)
};
let batch_count = batches.len();
let handles = batch_count
.checked_mul(collection.schema.fields().len())
.and_then(|count| count.checked_mul(size_of::<ArrayRef>()))
.ok_or_else(replay_metadata_overflow)?;
memory.try_resize(
memory
.size()
.checked_add(handles)
.ok_or_else(replay_metadata_overflow)?,
)?;
collection.batches = reserved_vec(batch_count, &memory, "replay metadata")?;
collection.cumulative_rows =
reserved_vec(batch_count, &memory, "replay metadata")?;
let key_rows = reserved_vec(batch_count, &memory, "replay metadata")?;
Ok(Self {
collection,
key_rows,
batches,
batch_offset,
last_batch_end,
expected_rows,
history_bounds,
memory,
})
}
pub(crate) fn advance_chunk(
&mut self,
history: &SharedHistoryBuffer,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<bool> {
if self.history_bounds != (history.head_index(), history.end_index()) {
return internal_err!(
"MATCH_RECOGNIZE history changed during replay preparation"
);
}
let mut work = CoarseWorkBatch::new(completed);
let result = (|| {
let stop = self.batches.start.saturating_add(256).min(self.batches.end);
while self.batches.start < stop {
let batch = history.batch(self.batches.start);
let end = if self.batches.start + 1 == self.batches.end {
self.last_batch_end
} else {
batch.num_rows()
};
let len = end.checked_sub(self.batch_offset).ok_or_else(|| {
DataFusionError::Internal(
"MATCH_RECOGNIZE replay batch has reversed bounds".into(),
)
})?;
let cumulative =
self.collection.num_rows().checked_add(len).ok_or_else(|| {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE replay row count exceeds usize".into(),
)
})?;
self.collection.batches.push(
if self.batch_offset == 0 && end == batch.num_rows() {
batch.clone()
} else {
batch.slice(self.batch_offset, len)
},
);
self.collection.cumulative_rows.push(cumulative);
self.key_rows.push(
history
.key_rows(self.batches.start)
.slice(self.batch_offset, len)?,
);
self.batches.start += 1;
self.batch_offset = 0;
work.complete_one()?;
}
let complete = self.batches.is_empty();
if complete && self.collection.num_rows() != self.expected_rows {
return internal_err!(
"MATCH_RECOGNIZE history replay contains {} rows, expected {}",
self.collection.num_rows(),
self.expected_rows
);
}
Ok(complete)
})();
work.finish_result(result)
}
pub(crate) fn into_parts(
self,
) -> (
BatchCollection,
Vec<crate::execution::matching::PartitionKeyRows>,
MemoryReservation,
) {
debug_assert!(self.batches.is_empty());
debug_assert_eq!(self.collection.num_rows(), self.expected_rows);
(self.collection, self.key_rows, self.memory)
}
}
fn replay_metadata_overflow() -> DataFusionError {
DataFusionError::ResourcesExhausted(
"MATCH_RECOGNIZE replay collection metadata exceeds usize".into(),
)
}
impl BatchCollection {
#[inline]
pub(crate) fn bound_batch(&self, batch: usize) -> Option<&BoundBatchColumns> {
self.bound.get(batch)
}
#[inline]
pub(crate) fn bound_row(
&self,
batch: usize,
local: usize,
) -> Option<BoundBatchRow<'_>> {
self.bound_batch(batch)?.row(local)
}
pub(crate) fn bind_input_chunk(
&mut self,
index: usize,
slots: &[usize],
memory: &MemoryReservation,
work: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<bool> {
if self.bound.is_empty() {
self.bound = reserved_vec(self.batches.len(), memory, "bound input columns")?;
}
let batch = &self.batches[index];
let width = slots
.last()
.map_or(0, |last| last + 1)
.min(batch.num_columns());
if self.bound.len() == index {
self.bound
.push(BoundBatchColumns::new(width, batch.num_rows(), memory)?);
}
let columns = &mut self.bound[index];
let advanced = columns.bind_chunk(batch, slots, width);
work(advanced.max(1))?;
Ok(columns.width() == width)
}
pub(crate) fn into_batches(self) -> Vec<RecordBatch> {
self.batches
}
pub(crate) fn into_retirement_parts(
self,
) -> (Vec<RecordBatch>, Vec<BoundBatchColumns>) {
(self.batches, self.bound)
}
pub(super) fn from_prepared_parts(
batches: Vec<RecordBatch>,
cumulative_rows: Vec<usize>,
schema: SchemaRef,
) -> Self {
debug_assert_eq!(batches.len(), cumulative_rows.len());
Self {
bound: Vec::new(),
batches,
cumulative_rows,
schema,
}
}
#[cfg(test)]
pub fn try_new(batches: Vec<RecordBatch>, schema: SchemaRef) -> Result<Self> {
let mut cum = 0usize;
let mut cumulative_rows = Vec::new();
cumulative_rows.try_reserve(batches.len()).map_err(|error| {
DataFusionError::ResourcesExhausted(format!(
"MATCH_RECOGNIZE collection could not reserve {} cumulative batch rows: {error}",
batches.len()
))
})?;
for batch in &batches {
let batch_rows = batch.num_rows();
cum = cum.checked_add(batch_rows).ok_or_else(|| {
DataFusionError::ResourcesExhausted(format!(
"MATCH_RECOGNIZE collection row count exceeds usize: {cum} existing rows plus {batch_rows} batch rows"
))
})?;
cumulative_rows.push(cum);
}
Ok(Self {
bound: Vec::new(),
batches,
cumulative_rows,
schema,
})
}
pub fn empty(schema: SchemaRef) -> Self {
Self {
bound: Vec::new(),
batches: Vec::new(),
cumulative_rows: Vec::new(),
schema,
}
}
#[inline]
pub fn num_rows(&self) -> usize {
self.cumulative_rows.last().copied().unwrap_or(0)
}
#[inline]
pub fn num_batches(&self) -> usize {
self.batches.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.batches.is_empty()
}
#[inline]
pub(in crate::execution) fn schema(&self) -> &SchemaRef {
&self.schema
}
#[inline]
pub fn locate(&self, global_row: usize) -> (usize, usize) {
debug_assert!(
global_row < self.num_rows(),
"BatchCollection::locate: global_row {} >= num_rows {}. Batches: {}",
global_row,
self.num_rows(),
self.batches.len()
);
if self.batches.len() == 1 {
return (0, global_row);
}
let batch_idx = self
.cumulative_rows
.partition_point(|&end| end <= global_row);
debug_assert_eq!(self.batches[batch_idx].schema(), self.schema);
let batch_start = if batch_idx == 0 {
0
} else {
self.cumulative_rows[batch_idx - 1]
};
(batch_idx, global_row - batch_start)
}
pub(crate) fn locate_with_work(
&self,
global_row: usize,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<(usize, usize)> {
if global_row >= self.num_rows() {
return datafusion_common::internal_err!(
"MATCH_RECOGNIZE collection row {global_row} is outside {} rows",
self.num_rows()
);
}
let location = self.locate(global_row);
completed(1)?;
Ok(location)
}
#[inline]
pub fn batch(&self, idx: usize) -> &RecordBatch {
&self.batches[idx]
}
pub(crate) fn replace_input_columns(
batch: RecordBatch,
schema: &SchemaRef,
replacements: &mut Vec<(usize, ArrayRef)>,
memory: &MemoryReservation,
) -> Result<RecordBatch> {
use datafusion::arrow::record_batch::RecordBatchOptions;
let (_, mut columns, rows) = batch.into_parts();
let width = schema.fields().len();
if width > columns.len() {
memory.try_grow(
width
.checked_mul(size_of::<ArrayRef>())
.ok_or_else(gather_size_overflow)?,
)?;
columns
.try_reserve_exact(width - columns.len())
.map_err(|e| {
DataFusionError::ResourcesExhausted(format!(
"MATCH_RECOGNIZE working batch columns: {e}"
))
})?;
replacements.sort_unstable_by_key(|(slot, _)| *slot);
}
for (slot, value) in replacements.drain(..) {
if slot >= width {
return internal_err!(
"MATCH_RECOGNIZE working column {slot} exceeds schema width {width}"
);
}
if slot == columns.len() {
columns.push(value);
} else if let Some(col) = columns.get_mut(slot) {
*col = value;
} else {
return internal_err!(
"MATCH_RECOGNIZE missing working column before slot {slot}"
);
}
}
let options = RecordBatchOptions::new().with_row_count(Some(rows));
Ok(RecordBatch::try_new_with_options(
schema.clone(),
columns,
&options,
)?)
}
pub(crate) fn push_input_view(
&mut self,
batch: RecordBatch,
memory: &MemoryReservation,
) -> Result<()> {
try_reserve_accounted(&mut self.batches, memory, 1, "input view metadata")?;
try_reserve_accounted(
&mut self.cumulative_rows,
memory,
1,
"input view metadata",
)?;
self.cumulative_rows.push(
self.num_rows()
.checked_add(batch.num_rows())
.ok_or_else(gather_size_overflow)?,
);
self.batches.push(batch);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
use datafusion::arrow::array::{Array, Int32Array};
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion_execution::memory_pool::{
GreedyMemoryPool, MemoryConsumer, MemoryPool,
};
use std::sync::Arc;
fn make_batch(start: i32, count: i32) -> RecordBatch {
let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
let values: Vec<i32> = (start..start + count).collect();
RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(values))]).unwrap()
}
#[test]
fn test_locate() {
let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
let batches = vec![make_batch(0, 10), make_batch(10, 20), make_batch(30, 5)];
let coll = BatchCollection::try_new(batches, schema).unwrap();
assert_eq!(coll.num_rows(), 35);
assert_eq!(coll.locate(0), (0, 0));
assert_eq!(coll.locate(9), (0, 9));
assert_eq!(coll.locate(10), (1, 0));
assert_eq!(coll.locate(29), (1, 19));
assert_eq!(coll.locate(30), (2, 0));
assert_eq!(coll.locate(34), (2, 4));
}
#[test]
fn single_batch_lookup_checks_bounds_and_reports_one_completed_unit() {
let batch = make_batch(10, 3);
let collection =
BatchCollection::try_new(vec![batch.clone()], batch.schema()).unwrap();
let mut charged = 0;
let mut completed = |n| {
charged += n;
Ok(())
};
assert_eq!(
collection.locate_with_work(2, &mut completed).unwrap(),
(0, 2)
);
assert!(collection.locate_with_work(3, &mut completed).is_err());
assert_eq!(charged, 1);
assert!(
collection
.locate_with_work(0, &mut |_| {
internal_err!("cancelled single-batch lookup")
})
.is_err()
);
}
fn get_values(coll: &BatchCollection) -> Vec<i32> {
let mut values = Vec::new();
for batch in &coll.batches {
let col = batch
.column(0)
.as_any()
.downcast_ref::<Int32Array>()
.unwrap();
values.extend(col.values().iter().copied());
}
values
}
fn injected_work_failure(target_report: usize) -> impl FnMut(usize) -> Result<()> {
let mut reports = 0usize;
move |units| {
assert!(units <= COARSE_WORK_BATCH_SIZE);
reports += 1;
if reports == target_report {
Err(DataFusionError::Execution(
"injected collection work failure".to_string(),
))
} else {
Ok(())
}
}
}
#[test]
fn replay_chunks_retain_admitted_metadata_until_release() -> Result<()> {
let limit = 1024 * 1024;
let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(limit));
let template = MemoryConsumer::new("replay-test").register(&pool);
let schema = make_batch(0, 1).schema();
let mut history =
SharedHistoryBuffer::new(Arc::clone(&schema), template.new_empty());
for batch in 0..258 {
history.append(make_batch(batch * 2, 2))?;
}
let history_bytes = pool.reserved();
let blocker = template.new_empty();
blocker.try_grow(limit - history_bytes)?;
let error = PreparingReplayCollection::try_new(
&history,
3,
515,
Arc::clone(&schema),
template.new_empty(),
)
.expect_err("replay metadata must be admitted before retaining slices");
assert!(matches!(error, DataFusionError::ResourcesExhausted(_)));
assert_eq!(pool.reserved(), limit);
assert_eq!((history.head_index(), history.end_index()), (0, 516));
drop(blocker);
assert_eq!(pool.reserved(), history_bytes);
let mut pending = PreparingReplayCollection::try_new(
&history,
3,
515,
Arc::clone(&schema),
template.new_empty(),
)?;
let admitted = pending.memory.size();
assert!(admitted > 0);
assert_eq!(pool.reserved(), history_bytes + admitted);
let mut work = 0;
assert!(!pending.advance_chunk(&history, &mut |units| {
assert!(units <= COARSE_WORK_BATCH_SIZE);
work += units;
Ok(())
})?);
assert_eq!(work, 256);
assert_eq!(pending.collection.num_batches(), 256);
assert_eq!(pending.collection.num_rows(), 511);
assert_eq!(pending.memory.size(), admitted);
assert_eq!(pool.reserved(), history_bytes + admitted);
drop(pending);
assert_eq!(pool.reserved(), history_bytes);
let mut pending = PreparingReplayCollection::try_new(
&history,
3,
515,
schema,
template.new_empty(),
)?;
pending
.advance_chunk(&history, &mut injected_work_failure(1))
.expect_err("cancellation must preserve the last completed slice cursor");
assert_eq!(pending.collection.num_batches(), COARSE_WORK_BATCH_SIZE);
while !pending.advance_chunk(&history, &mut |_| Ok(()))? {}
let (collection, key_rows, memory) = pending.into_parts();
assert_eq!(get_values(&collection), (3..515).collect::<Vec<_>>());
assert_eq!(collection.num_batches(), 257);
assert_eq!(collection.batch(0).num_rows(), 1);
assert_eq!(collection.batch(256).num_rows(), 1);
let key_bytes = key_rows.capacity()
* size_of::<crate::execution::matching::PartitionKeyRows>();
assert!(memory.size() > 0);
drop(key_rows);
memory.try_shrink(key_bytes)?;
let mut remainder = PreparingReplayCollection::try_new(
&history,
515,
516,
collection.schema().clone(),
template.new_empty(),
)?;
let mut work = 0;
assert!(remainder.advance_chunk(&history, &mut |units| {
work += units;
Ok(())
})?);
assert_eq!(work, 1);
let (remainder, keys, remainder_memory) = remainder.into_parts();
assert_eq!(keys.len(), 1);
assert_eq!(get_values(&remainder), [515]);
assert_eq!(get_values(&collection), (3..515).collect::<Vec<_>>());
assert_eq!(remainder.num_batches(), 1);
assert_eq!(remainder.batch(0).num_rows(), 1);
assert!(remainder_memory.size() > 0);
assert_eq!(
pool.reserved(),
history_bytes + memory.size() + remainder_memory.size()
);
drop(remainder);
drop(keys);
drop(remainder_memory);
assert_eq!(pool.reserved(), history_bytes + memory.size());
drop(collection);
drop(memory);
assert_eq!(pool.reserved(), history_bytes);
drop(history);
assert_eq!(pool.reserved(), 0);
Ok(())
}
}