use std::ops::Range;
use std::sync::Arc;
use datafusion::arrow::array::{ArrayRef, make_comparator};
use datafusion::arrow::datatypes::SchemaRef;
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::Result;
use datafusion::execution::memory_pool::MemoryReservation;
use datafusion::physical_expr_common::sort_expr::PhysicalSortExpr;
use crate::execution::matching::{
PartitionKey, PartitionKeyRows, PartitionKeySchema, shared_empty_partition_key,
};
use crate::execution::storage::bound_columns::BoundBatchColumns;
use crate::execution::storage::collection::BatchCollection;
mod grouped;
mod input;
pub(crate) use grouped::GroupedRanges;
mod keys;
mod selection;
pub(in crate::execution) fn same_partition_rows(
left: &ArrayRef,
left_row: usize,
right: &ArrayRef,
right_row: usize,
) -> Result<bool> {
let left = left.slice(left_row, 1);
let right = right.slice(right_row, 1);
let compare = make_comparator(left.as_ref(), right.as_ref(), Default::default())?;
Ok(compare(0, 0).is_eq())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PhysicalHeadEnd {
OpenTail,
PartitionBoundary,
InputEnd,
}
impl PhysicalHeadEnd {
pub(crate) const fn ends_partition(self) -> bool {
!matches!(self, Self::OpenTail)
}
}
pub(crate) struct RawPhysicalHead {
collection: BatchCollection,
partitions: HeadPartitions,
}
pub(crate) struct HeadPartitions {
pub(crate) continues_tail: bool,
pub(crate) ranges: Vec<Range<usize>>,
pub(crate) open_key: Option<PartitionKeyRows>,
pub(crate) end: PhysicalHeadEnd,
}
impl HeadPartitions {
pub(crate) fn open_key(&self) -> Result<PartitionKey> {
self.open_key
.as_ref()
.ok_or_else(|| {
datafusion::common::internal_datafusion_err!(
"MATCH_RECOGNIZE open partition has no input representative"
)
})?
.key(0)
}
}
pub(crate) struct RetiringHead {
batches: std::vec::IntoIter<RecordBatch>,
bound: std::vec::IntoIter<BoundBatchColumns>,
pub(crate) memory: MemoryReservation,
}
impl RetiringHead {
pub(crate) fn new(collection: BatchCollection, memory: MemoryReservation) -> Self {
let (batches, bound) = collection.into_retirement_parts();
Self {
batches: batches.into_iter(),
bound: bound.into_iter(),
memory,
}
}
pub(crate) fn advance_chunk(
&mut self,
completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<bool> {
if let Some(columns) = self.bound.next() {
let units = columns.width() + 1;
drop(columns);
completed(units)?;
} else if let Some(batch) = self.batches.next() {
let units = batch.num_columns() + 1;
drop(batch);
completed(units)?;
} else {
return Ok(true);
}
Ok(false)
}
pub(crate) fn into_memory(self) -> MemoryReservation {
debug_assert!(self.batches.as_slice().is_empty());
debug_assert!(self.bound.as_slice().is_empty());
self.memory
}
}
impl RawPhysicalHead {
pub(crate) fn into_retirement(self, memory: MemoryReservation) -> RetiringHead {
let (collection, _) = self.into_parts();
RetiringHead::new(collection, memory)
}
pub(crate) fn empty_input_end(schema: SchemaRef) -> Self {
Self {
collection: BatchCollection::empty(schema),
partitions: HeadPartitions {
ranges: Vec::new(),
continues_tail: false,
open_key: None,
end: PhysicalHeadEnd::InputEnd,
},
}
}
pub(crate) fn num_rows(&self) -> usize {
self.collection.num_rows()
}
pub(crate) const fn end(&self) -> PhysicalHeadEnd {
self.partitions.end
}
pub(crate) fn into_parts(self) -> (BatchCollection, HeadPartitions) {
(self.collection, self.partitions)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FlushPolicy {
RowThreshold(usize),
LogicalPartitionBoundaryOnly,
}
impl FlushPolicy {
const fn threshold_reached(self, buffered_rows: usize) -> bool {
match self {
Self::RowThreshold(threshold) => buffered_rows >= threshold,
Self::LogicalPartitionBoundaryOnly => false,
}
}
}
pub struct PartitionedBuffer {
batches: Vec<RecordBatch>,
partition_columns: Vec<PartitionKeyRows>,
buffered_rows: usize,
flush_policy: FlushPolicy,
schema: SchemaRef,
partition_by_sort_keys: Arc<[PhysicalSortExpr]>,
key_schema: Option<Arc<PartitionKeySchema>>,
guaranteed_safe_rows: usize,
selection_memory: Option<MemoryReservation>,
}
impl PartitionedBuffer {
pub fn schema(&self) -> SchemaRef {
Arc::clone(&self.schema)
}
pub fn new(
schema: SchemaRef,
partition_by_sort_keys: Vec<PhysicalSortExpr>,
flush_threshold: usize,
) -> Self {
Self::new_with_policy(
schema,
partition_by_sort_keys,
FlushPolicy::RowThreshold(flush_threshold),
)
}
pub(crate) fn new_at_logical_partition_boundaries(
schema: SchemaRef,
partition_by_sort_keys: Vec<PhysicalSortExpr>,
) -> Self {
Self::new_with_policy(
schema,
partition_by_sort_keys,
FlushPolicy::LogicalPartitionBoundaryOnly,
)
}
fn new_with_policy(
schema: SchemaRef,
partition_by_sort_keys: Vec<PhysicalSortExpr>,
flush_policy: FlushPolicy,
) -> Self {
Self {
batches: Vec::new(),
partition_columns: Vec::new(),
buffered_rows: 0,
flush_policy,
schema,
partition_by_sort_keys: partition_by_sort_keys.into(),
key_schema: None,
guaranteed_safe_rows: 0,
selection_memory: None,
}
}
#[cfg(test)]
fn try_append(&mut self, batch: RecordBatch) -> Result<bool> {
use crate::execution::common::scheduling::SliceControl;
use crate::execution::common::work::WorkGovernor;
use crate::execution::storage::history_buffer::SharedHistoryBuffer;
use datafusion::execution::memory_pool::{
MemoryConsumer, MemoryPool, UnboundedMemoryPool,
};
if batch.num_rows() == 0 {
return Ok(true);
}
let pool: Arc<dyn MemoryPool> = Arc::new(UnboundedMemoryPool::default());
let memory = MemoryConsumer::new("buffer-input-test").register(&pool);
let mut history =
SharedHistoryBuffer::new(Arc::clone(&self.schema), memory.new_empty());
let input_memory = history.admit_input(&batch, false)?;
let mut governor = WorkGovernor::default();
let (same_key, _) = futures::executor::block_on(self.admit_ordered_input(
batch,
input_memory,
None,
None,
None,
&mut history,
&mut governor,
&SliceControl::default(),
|| false,
))?;
Ok(same_key)
}
pub(crate) fn has_partition_by(&self) -> bool {
!self.partition_by_sort_keys.is_empty()
}
pub fn is_full(&self) -> bool {
self.flush_policy.threshold_reached(self.buffered_rows)
}
pub fn buffered_rows(&self) -> usize {
self.buffered_rows
}
#[cfg(test)]
fn take_processable(&mut self, final_flush: bool) -> Result<Option<BatchCollection>> {
Ok(self
.take_processable_plan(final_flush)?
.map(|head| head.collection))
}
#[cfg(test)]
fn take_processable_plan(
&mut self,
final_flush: bool,
) -> Result<Option<RawPhysicalHead>> {
use crate::execution::common::scheduling::SliceControl;
use crate::execution::common::work::WorkGovernor;
let mut governor = WorkGovernor::default();
self.take_processable_plan_with_governor(
final_flush,
&mut governor,
&SliceControl::default(),
|| false,
)
}
#[cfg(test)]
fn take_processable_plan_with_governor(
&mut self,
final_flush: bool,
governor: &mut crate::execution::common::work::WorkGovernor,
slice: &crate::execution::common::scheduling::SliceControl,
is_aborted: impl Fn() -> bool,
) -> Result<Option<RawPhysicalHead>> {
use datafusion::execution::memory_pool::{
MemoryConsumer, MemoryPool, UnboundedMemoryPool,
};
let pool: Arc<dyn MemoryPool> = Arc::new(UnboundedMemoryPool::default());
let memory = MemoryConsumer::new("buffer-selection-test").register(&pool);
let (head, _) = futures::executor::block_on(self.select_head(
final_flush,
None,
memory,
governor,
slice,
is_aborted,
))?;
Ok(head)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct SegmentCursor {
position: usize,
first: LeadingSegment,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum LeadingSegment {
#[default]
Fresh,
Previous,
ImplicitEmpty,
}
pub(crate) struct HeadSegment {
pub(crate) range: Range<usize>,
pub(crate) ends_partition: bool,
pub(crate) fresh_index: Option<usize>,
}
impl HeadSegment {
pub(crate) fn key(
&self,
head: &HeadPartitions,
partitioned: bool,
previous: Option<&PartitionKey>,
) -> Result<Option<PartitionKey>> {
match self.fresh_index {
None => previous.cloned().map(Some).ok_or_else(|| {
datafusion::common::internal_datafusion_err!(
"MATCH_RECOGNIZE continued segment has no open logical key"
)
}),
Some(_) if self.ends_partition => Ok(None),
Some(_) if partitioned => head.open_key().map(Some),
Some(_) => Ok(Some(shared_empty_partition_key())),
}
}
}
impl SegmentCursor {
pub(crate) fn new(previous: bool, implicit_empty: bool) -> Self {
let first = if previous {
LeadingSegment::Previous
} else if implicit_empty {
LeadingSegment::ImplicitEmpty
} else {
LeadingSegment::Fresh
};
Self { position: 0, first }
}
pub(crate) fn peek(mut self, head: &HeadPartitions) -> Option<HeadSegment> {
self.next_segment(head)
}
pub(crate) fn next_segment(&mut self, head: &HeadPartitions) -> Option<HeadSegment> {
let position = self.position;
let previous = self.first == LeadingSegment::Previous;
let continued_range = previous && head.continues_tail;
let leading_close = previous && !continued_range;
let (range, closes) = if position == 0 && leading_close {
(0..0, true)
} else if self.first == LeadingSegment::ImplicitEmpty {
if position != 0 {
return None;
}
(0..0, head.end.ends_partition())
} else {
let index = position - usize::from(leading_close);
let range = head.ranges.get(index)?.clone();
(
range,
index + 1 < head.ranges.len() || head.end.ends_partition(),
)
};
let fresh_index = position.checked_sub(usize::from(previous));
self.position += 1;
Some(HeadSegment {
range,
ends_partition: closes,
fresh_index,
})
}
}
#[cfg(test)]
mod tests;