Apache DataFusion SQL Query Engine
Use arrow row format in SortPreservingMerge (#3386)
Raphael Taylor-Davies451e44140260
diff --git a/datafusion/core/src/physical_plan/sorts/cursor.rs b/datafusion/core/src/physical_plan/sorts/cursor.rsindex d2cc528a3d..c9313fbfe2 100644--- a/datafusion/core/src/physical_plan/sorts/cursor.rs+++ b/datafusion/core/src/physical_plan/sorts/cursor.rs@@ -15,17 +15,8 @@// specific language governing permissions and limitations// under the License.-use crate::error;-use crate::error::{DataFusionError, Result};-use crate::physical_plan::PhysicalExpr;-use arrow::array::{ArrayRef, DynComparator};-use arrow::compute::SortOptions;-use arrow::record_batch::RecordBatch;-use hashbrown::HashMap;-use parking_lot::RwLock;-use std::borrow::BorrowMut;+use arrow::row::{Row, Rows};use std::cmp::Ordering;-use std::sync::Arc;/// A `SortKeyCursor` is created from a `RecordBatch`, and a set of/// `PhysicalExpr` that when evaluated on the `RecordBatch` yield the sort keys.@@ -38,54 +29,35 @@ use std::sync::Arc;/// a row comparator for each other cursor that it is compared to.pub struct SortKeyCursor {stream_idx: usize,- sort_columns: Vec<ArrayRef>,cur_row: usize,num_rows: usize,// An id uniquely identifying the record batch scanned by this cursor.batch_id: usize,- // A collection of comparators that compare rows in this cursor's batch to- // the cursors in other batches. Other batches are uniquely identified by- // their batch_idx.- batch_comparators: RwLock<HashMap<usize, Vec<DynComparator>>>,- sort_options: Arc<Vec<SortOptions>>,+ rows: Rows,}impl std::fmt::Debug for SortKeyCursor {fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {f.debug_struct("SortKeyCursor")- .field("sort_columns", &self.sort_columns).field("cur_row", &self.cur_row).field("num_rows", &self.num_rows).field("batch_id", &self.batch_id)- .field("batch_comparators", &"<FUNC>").finish()}}impl SortKeyCursor {/// Create a new SortKeyCursor- pub fn new(- stream_idx: usize,- batch_id: usize,- batch: &RecordBatch,- sort_key: &[Arc<dyn PhysicalExpr>],- sort_options: Arc<Vec<SortOptions>>,- ) -> error::Result<Self> {- let sort_columns = sort_key- .iter()- .map(|expr| Ok(expr.evaluate(batch)?.into_array(batch.num_rows())))- .collect::<error::Result<_>>()?;- Ok(Self {+ pub fn new(stream_idx: usize, batch_id: usize, rows: Rows) -> Self {+ Self {stream_idx,cur_row: 0,- num_rows: batch.num_rows(),- sort_columns,+ num_rows: rows.num_rows(),batch_id,- batch_comparators: RwLock::new(HashMap::new()),- sort_options,- })+ rows,+ }}#[inline(always)]@@ -115,99 +87,15 @@ impl SortKeyCursor {t}- /// Compares the sort key pointed to by this instance's row cursor with that of another- pub fn compare(&self, other: &SortKeyCursor) -> error::Result<Ordering> {- if self.sort_columns.len() != other.sort_columns.len() {- return Err(DataFusionError::Internal(format!(- "SortKeyCursors had inconsistent column counts: {} vs {}",- self.sort_columns.len(),- other.sort_columns.len()- )));- }-- if self.sort_columns.len() != self.sort_options.len() {- return Err(DataFusionError::Internal(format!(- "Incorrect number of SortOptions provided to SortKeyCursor::compare, expected {} got {}",- self.sort_columns.len(),- self.sort_options.len()- )));- }-- let zipped: Vec<((&ArrayRef, &ArrayRef), &SortOptions)> = self- .sort_columns- .iter()- .zip(other.sort_columns.iter())- .zip(self.sort_options.iter())- .collect::<Vec<_>>();-- self.init_cmp_if_needed(other, &zipped)?;- let map = self.batch_comparators.read();- let cmp = map.get(&other.batch_id).ok_or_else(|| {- DataFusionError::Execution(format!(- "Failed to find comparator for {} cmp {}",- self.batch_id, other.batch_id- ))- })?;-- for (i, ((l, r), sort_options)) in zipped.iter().enumerate() {- match (l.is_valid(self.cur_row), r.is_valid(other.cur_row)) {- (false, true) if sort_options.nulls_first => return Ok(Ordering::Less),- (false, true) => return Ok(Ordering::Greater),- (true, false) if sort_options.nulls_first => {- return Ok(Ordering::Greater)- }- (true, false) => return Ok(Ordering::Less),- (false, false) => {}- (true, true) => match cmp[i](self.cur_row, other.cur_row) {- Ordering::Equal => {}- o if sort_options.descending => return Ok(o.reverse()),- o => return Ok(o),- },- }- }-- // Break ties using stream_idx to ensure a predictable- // ordering of rows when comparing equal streams.- Ok(self.stream_idx.cmp(&other.stream_idx))- }-- /// Initialize a collection of comparators for comparing- /// columnar arrays of this cursor and "other" if needed.- fn init_cmp_if_needed(- &self,- other: &SortKeyCursor,- zipped: &[((&ArrayRef, &ArrayRef), &SortOptions)],- ) -> Result<()> {- let hm = self.batch_comparators.read();- if !hm.contains_key(&other.batch_id) {- drop(hm);- let mut map = self.batch_comparators.write();- let cmp = map- .borrow_mut()- .entry(other.batch_id)- .or_insert_with(|| Vec::with_capacity(other.sort_columns.len()));-- for (i, ((l, r), _)) in zipped.iter().enumerate() {- if i >= cmp.len() {- // initialise comparators- cmp.push(arrow::array::build_compare(l.as_ref(), r.as_ref())?);- }- }- }- Ok(())- }-}--impl Ord for SortKeyCursor {- /// Needed by min-heap comparison and reverse the order at the same time.- fn cmp(&self, other: &Self) -> Ordering {- other.compare(self).unwrap()+ /// Returns the current row+ fn current(&self) -> Row<'_> {+ self.rows.row(self.cur_row)}}impl PartialEq for SortKeyCursor {fn eq(&self, other: &Self) -> bool {- other.compare(self).unwrap() == Ordering::Equal+ self.current() == other.current()}}@@ -215,6 +103,14 @@ impl Eq for SortKeyCursor {}impl PartialOrd for SortKeyCursor {fn partial_cmp(&self, other: &Self) -> Option<Ordering> {- other.compare(self).ok()+ Some(self.cmp(other))+ }+}++impl Ord for SortKeyCursor {+ fn cmp(&self, other: &Self) -> Ordering {+ self.current()+ .cmp(&other.current())+ .then_with(|| self.stream_idx.cmp(&other.stream_idx))}}diff --git a/datafusion/core/src/physical_plan/sorts/sort.rs b/datafusion/core/src/physical_plan/sorts/sort.rsindex fb9bb10a38..e338ead86d 100644--- a/datafusion/core/src/physical_plan/sorts/sort.rs+++ b/datafusion/core/src/physical_plan/sorts/sort.rs@@ -188,7 +188,7 @@ impl ExternalSorter {&self.expr,tracking_metrics,self.session_config.batch_size(),- )))+ )?))} else if in_mem_batches.len() > 0 {let tracking_metrics = self.metrics_setdiff --git a/datafusion/core/src/physical_plan/sorts/sort_preserving_merge.rs b/datafusion/core/src/physical_plan/sorts/sort_preserving_merge.rsindex 5db3c50e6c..22bd83ec9a 100644--- a/datafusion/core/src/physical_plan/sorts/sort_preserving_merge.rs+++ b/datafusion/core/src/physical_plan/sorts/sort_preserving_merge.rs@@ -17,30 +17,31 @@//! Defines the sort preserving merge plan-use crate::physical_plan::metrics::{- ExecutionPlanMetricsSet, MemTrackingMetrics, MetricsSet,-};-use log::debug;-use parking_lot::Mutex;use std::any::Any;+use std::cmp::Reverse;use std::collections::{BinaryHeap, VecDeque};use std::pin::Pin;use std::sync::Arc;use std::task::{Context, Poll};+use arrow::error::ArrowError;+use arrow::row::{RowConverter, SortField};use arrow::{array::{make_array as make_arrow_array, MutableArrayData},- compute::SortOptions,datatypes::SchemaRef,- error::{ArrowError, Result as ArrowResult},+ error::Result as ArrowResult,record_batch::RecordBatch,};use futures::stream::{Fuse, FusedStream};use futures::{Stream, StreamExt};+use log::debug;use tokio::sync::mpsc;use crate::error::{DataFusionError, Result};use crate::execution::context::TaskContext;+use crate::physical_plan::metrics::{+ ExecutionPlanMetricsSet, MemTrackingMetrics, MetricsSet,+};use crate::physical_plan::sorts::{RowIndex, SortKeyCursor, SortedStream};use crate::physical_plan::stream::RecordBatchReceiverStream;use crate::physical_plan::{@@ -225,7 +226,7 @@ impl ExecutionPlan for SortPreservingMergeExec {&self.expr,tracking_metrics,context.session_config().batch_size(),- ));+ )?);debug!("Got stream result from SortPreservingMergeStream::new_from_receivers");@@ -258,7 +259,7 @@ impl ExecutionPlan for SortPreservingMergeExec {struct MergingStreams {/// The sorted input streams to merge together- streams: Mutex<Vec<Fuse<SendableRecordBatchStream>>>,+ streams: Vec<Fuse<SendableRecordBatchStream>>,/// number of streamsnum_streams: usize,}@@ -275,7 +276,7 @@ impl MergingStreams {fn new(input_streams: Vec<Fuse<SendableRecordBatchStream>>) -> Self {Self {num_streams: input_streams.len(),- streams: Mutex::new(input_streams),+ streams: input_streams,}}@@ -308,9 +309,6 @@ pub(crate) struct SortPreservingMergeStream {/// The physical expressions to sort bycolumn_expressions: Vec<Arc<dyn PhysicalExpr>>,- /// The sort options for each expression- sort_options: Arc<Vec<SortOptions>>,-/// used to record execution metricstracking_metrics: MemTrackingMetrics,@@ -320,11 +318,14 @@ pub(crate) struct SortPreservingMergeStream {/// An id to uniquely identify the input stream batchnext_batch_id: usize,- /// min heap for record comparison- min_heap: BinaryHeap<SortKeyCursor>,+ /// Heap that yields [`SortKeyCursor`] in increasing order+ heap: BinaryHeap<Reverse<SortKeyCursor>>,/// target batch sizebatch_size: usize,++ /// row converter+ row_converter: RowConverter,}impl SortPreservingMergeStream {@@ -334,7 +335,7 @@ impl SortPreservingMergeStream {expressions: &[PhysicalSortExpr],tracking_metrics: MemTrackingMetrics,batch_size: usize,- ) -> Self {+ ) -> Result<Self> {let stream_count = streams.len();let batches = (0..stream_count).into_iter()@@ -343,20 +344,29 @@ impl SortPreservingMergeStream {tracking_metrics.init_mem_used(streams.iter().map(|s| s.mem_used).sum());let wrappers = streams.into_iter().map(|s| s.stream.fuse()).collect();- Self {+ let sort_fields = expressions+ .iter()+ .map(|expr| {+ let data_type = expr.expr.data_type(&schema)?;+ Ok(SortField::new_with_options(data_type, expr.options))+ })+ .collect::<Result<Vec<_>>>()?;+ let row_converter = RowConverter::new(sort_fields);++ Ok(Self {schema,batches,cursor_finished: vec![true; stream_count],streams: MergingStreams::new(wrappers),column_expressions: expressions.iter().map(|x| x.expr.clone()).collect(),- sort_options: Arc::new(expressions.iter().map(|x| x.options).collect()),tracking_metrics,aborted: false,in_progress: vec![],next_batch_id: 0,- min_heap: BinaryHeap::with_capacity(stream_count),+ heap: BinaryHeap::with_capacity(stream_count),batch_size,- }+ row_converter,+ })}/// If the stream at the given index is not exhausted, and the last cursor for the@@ -373,9 +383,7 @@ impl SortPreservingMergeStream {}let mut empty_batch = false;{- let mut streams = self.streams.streams.lock();-- let stream = &mut streams[idx];+ let stream = &mut self.streams.streams[idx];if stream.is_terminated() {return Poll::Ready(Ok(()));}@@ -388,22 +396,30 @@ impl SortPreservingMergeStream {}Some(Ok(batch)) => {if batch.num_rows() > 0 {- let cursor = match SortKeyCursor::new(- idx,- self.next_batch_id, // assign this batch an ID- &batch,- &self.column_expressions,- self.sort_options.clone(),- ) {- Ok(cursor) => cursor,+ let cols = self+ .column_expressions+ .iter()+ .map(|expr| {+ Ok(expr.evaluate(&batch)?.into_array(batch.num_rows()))+ })+ .collect::<Result<Vec<_>>>()?;++ let rows = match self.row_converter.convert_columns(&cols) {+ Ok(rows) => rows,Err(e) => {return Poll::Ready(Err(ArrowError::ExternalError(Box::new(e),)));}};++ let cursor = SortKeyCursor::new(+ idx,+ self.next_batch_id, // assign this batch an ID+ rows,+ );self.next_batch_id += 1;- self.min_heap.push(cursor);+ self.heap.push(Reverse(cursor));self.cursor_finished[idx] = false;self.batches[idx].push_back(batch)} else {@@ -543,22 +559,22 @@ impl SortPreservingMergeStream {}}- loop {- // NB timer records time taken on drop, so there are no- // calls to `timer.done()` below.- let elapsed_compute = self.tracking_metrics.elapsed_compute().clone();- let _timer = elapsed_compute.timer();+ // NB timer records time taken on drop, so there are no+ // calls to `timer.done()` below.+ let elapsed_compute = self.tracking_metrics.elapsed_compute().clone();+ let _timer = elapsed_compute.timer();- match self.min_heap.pop() {- Some(mut cursor) => {+ loop {+ match self.heap.pop() {+ Some(Reverse(mut cursor)) => {let stream_idx = cursor.stream_idx();let batch_idx = self.batches[stream_idx].len() - 1;let row_idx = cursor.advance();let mut cursor_finished = false;- // insert the cursor back to min_heap if the record batch is not exhausted+ // insert the cursor back to heap if the record batch is not exhaustedif !cursor.is_finished() {- self.min_heap.push(cursor);+ self.heap.push(Reverse(cursor));} else {cursor_finished = true;self.cursor_finished[stream_idx] = true;@@ -601,26 +617,28 @@ impl RecordBatchStream for SortPreservingMergeStream {#[cfg(test)]mod tests {- use crate::from_slice::FromSlice;- use crate::physical_plan::metrics::MetricValue;- use crate::test::exec::{assert_strong_count_converges_to_zero, BlockingExec};- use arrow::array::ArrayRef;use std::iter::FromIterator;+ use arrow::array::ArrayRef;+ use arrow::compute::SortOptions;+ use arrow::datatypes::{DataType, Field, Schema};+ use futures::FutureExt;+ use tokio_stream::StreamExt;+use crate::arrow::array::{Int32Array, StringArray, TimestampNanosecondArray};+ use crate::from_slice::FromSlice;use crate::physical_plan::coalesce_partitions::CoalescePartitionsExec;use crate::physical_plan::expressions::col;use crate::physical_plan::memory::MemoryExec;+ use crate::physical_plan::metrics::MetricValue;use crate::physical_plan::sorts::sort::SortExec;use crate::physical_plan::{collect, common};+ use crate::prelude::{SessionConfig, SessionContext};+ use crate::test::exec::{assert_strong_count_converges_to_zero, BlockingExec};use crate::test::{self, assert_is_pending};use crate::{assert_batches_eq, test_util};use super::*;- use crate::prelude::{SessionConfig, SessionContext};- use arrow::datatypes::{DataType, Field, Schema};- use futures::FutureExt;- use tokio_stream::StreamExt;#[tokio::test]async fn test_merge_interleave() {@@ -1195,7 +1213,8 @@ mod tests {sort.as_slice(),tracking_metrics,task_ctx.session_config().batch_size(),- );+ )+ .unwrap();let mut merged = common::collect(Box::pin(merge_stream)).await.unwrap();diff --git a/datafusion/core/tests/sort_key_cursor.rs b/datafusion/core/tests/sort_key_cursor.rsindex 7672ea577b..c5e748c97b 100644--- a/datafusion/core/tests/sort_key_cursor.rs+++ b/datafusion/core/tests/sort_key_cursor.rs@@ -19,24 +19,26 @@use std::{cmp::Ordering, sync::Arc};-use arrow::{array::Int64Array, compute::SortOptions, record_batch::RecordBatch};+use arrow::datatypes::DataType;+use arrow::row::{RowConverter, SortField};+use arrow::{array::Int64Array, record_batch::RecordBatch};use datafusion::physical_plan::sorts::{RowIndex, SortKeyCursor};-use datafusion_physical_expr::expressions::col;#[test]fn test_single_column() {+ let mut converter = RowConverter::new(vec![SortField::new(DataType::Int64)]);let batch1 = int64_batch(vec![Some(1), Some(2), Some(5), Some(6)]);let batch2 = int64_batch(vec![Some(3), Some(4), Some(8), Some(9)]);let mut cursor1 = CursorBuilder::new(batch1).with_stream_idx(11).with_batch_id(0)- .build();+ .build(&mut converter);let mut cursor2 = CursorBuilder::new(batch2).with_stream_idx(22).with_batch_id(0)- .build();+ .build(&mut converter);let expected = vec!["11: (0, 0)",@@ -54,6 +56,7 @@ fn test_single_column() {#[test]fn test_stable_compare() {+ let mut converter = RowConverter::new(vec![SortField::new(DataType::Int64)]);// Validate ties are broken by the lower stream idx to ensure stable sortlet batch1 = int64_batch(vec![Some(3), Some(4)]);let batch2 = int64_batch(vec![Some(3)]);@@ -73,9 +76,18 @@ fn test_stable_compare() {// Output should be the same, regardless of orderassert_indexes(&expected,- run(&mut cursor1.clone().build(), &mut cursor2.clone().build()),+ run(+ &mut cursor1.clone().build(&mut converter),+ &mut cursor2.clone().build(&mut converter),+ ),+ );+ assert_indexes(+ &expected,+ run(+ &mut cursor2.build(&mut converter),+ &mut cursor1.build(&mut converter),+ ),);- assert_indexes(&expected, run(&mut cursor2.build(), &mut cursor1.build()));}/// Runs the two cursors to completion, sorting them, and@@ -94,7 +106,7 @@ fn run(cursor1: &mut SortKeyCursor, cursor2: &mut SortKeyCursor) -> Vec<RowIndex(true, false) => return drain(cursor2, indexes),(false, true) => return drain(cursor1, indexes),// both cursors have more rows- (false, false) => match cursor1.compare(cursor2).unwrap() {+ (false, false) => match cursor1.cmp(&cursor2) {Ordering::Less => {indexes.push(advance(cursor1));}@@ -164,25 +176,18 @@ impl CursorBuilder {self}- fn build(self) -> SortKeyCursor {+ fn build(self, converter: &mut RowConverter) -> SortKeyCursor {let Self {batch,stream_idx,batch_id,} = self;- let c1 = col("c1", &batch.schema()).unwrap();- let sort_key = vec![c1];-- let sort_options = Arc::new(vec![SortOptions::default()]);-+ let rows = converter.convert_columns(batch.columns()).unwrap();SortKeyCursor::new(stream_idx.expect("stream idx not set"),batch_id.expect("batch id not set"),- &batch,- &sort_key,- sort_options,+ rows,)- .unwrap()}}