Skip to content

Apache DataFusion SQL Query Engine

Automatically split large single RecordBatches in `MemorySource` into smaller batches (#16734)

kosiew63dd4e27db1d
diff --git a/datafusion/core/src/datasource/listing/table.rs b/datafusion/core/src/datasource/listing/table.rs
index d1cb32113f..873ff7958d 100644
--- a/datafusion/core/src/datasource/listing/table.rs
+++ b/datafusion/core/src/datasource/listing/table.rs
@@ -2026,7 +2026,6 @@ mod tests {
#[tokio::test]
async fn test_insert_into_append_new_parquet_files_session_overrides() -> Result<()> {
let mut config_map: HashMap<String, String> = HashMap::new();
- config_map.insert("datafusion.execution.batch_size".into(), "10".into());
config_map.insert(
"datafusion.execution.soft_max_rows_per_output_file".into(),
"10".into(),
@@ -2091,7 +2090,7 @@ mod tests {
"datafusion.execution.parquet.write_batch_size".into(),
"5".into(),
);
- config_map.insert("datafusion.execution.batch_size".into(), "1".into());
+ config_map.insert("datafusion.execution.batch_size".into(), "10".into());
helper_test_append_new_files_to_table(
ParquetFormat::default().get_ext(),
FileCompressionType::UNCOMPRESSED,
diff --git a/datafusion/core/tests/execution/datasource_split.rs b/datafusion/core/tests/execution/datasource_split.rs
new file mode 100644
index 0000000000..0b90c6f326
--- /dev/null
+++ b/datafusion/core/tests/execution/datasource_split.rs
@@ -0,0 +1,123 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use arrow::{
+ array::{ArrayRef, Int32Array},
+ datatypes::{DataType, Field, Schema},
+ record_batch::RecordBatch,
+};
+use datafusion_datasource::memory::MemorySourceConfig;
+use datafusion_execution::TaskContext;
+use datafusion_physical_plan::{common::collect, ExecutionPlan};
+use std::sync::Arc;
+
+/// Helper function to create a memory source with the given batch size and collect all batches
+async fn create_and_collect_batches(
+ batch_size: usize,
+) -> datafusion_common::Result<Vec<RecordBatch>> {
+ let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
+ let array = Int32Array::from_iter_values(0..batch_size as i32);
+ let batch = RecordBatch::try_new(schema.clone(), vec![Arc::new(array) as ArrayRef])?;
+ let exec = MemorySourceConfig::try_new_exec(&[vec![batch]], schema, None)?;
+ let ctx = Arc::new(TaskContext::default());
+ let stream = exec.execute(0, ctx)?;
+ collect(stream).await
+}
+
+/// Helper function to create a memory source with multiple batches and collect all results
+async fn create_and_collect_multiple_batches(
+ input_batches: Vec<RecordBatch>,
+) -> datafusion_common::Result<Vec<RecordBatch>> {
+ let schema = input_batches[0].schema();
+ let exec = MemorySourceConfig::try_new_exec(&[input_batches], schema, None)?;
+ let ctx = Arc::new(TaskContext::default());
+ let stream = exec.execute(0, ctx)?;
+ collect(stream).await
+}
+
+#[tokio::test]
+async fn datasource_splits_large_batches() -> datafusion_common::Result<()> {
+ let batch_size = 20000;
+ let batches = create_and_collect_batches(batch_size).await?;
+
+ assert!(batches.len() > 1);
+ let max = batches.iter().map(|b| b.num_rows()).max().unwrap();
+ assert!(
+ max <= datafusion_execution::config::SessionConfig::new()
+ .options()
+ .execution
+ .batch_size
+ );
+ let total: usize = batches.iter().map(|b| b.num_rows()).sum();
+ assert_eq!(total, batch_size);
+ Ok(())
+}
+
+#[tokio::test]
+async fn datasource_exact_batch_size_no_split() -> datafusion_common::Result<()> {
+ let session_config = datafusion_execution::config::SessionConfig::new();
+ let configured_batch_size = session_config.options().execution.batch_size;
+
+ let batches = create_and_collect_batches(configured_batch_size).await?;
+
+ // Should not split when exactly equal to batch_size
+ assert_eq!(batches.len(), 1);
+ assert_eq!(batches[0].num_rows(), configured_batch_size);
+ Ok(())
+}
+
+#[tokio::test]
+async fn datasource_small_batch_no_split() -> datafusion_common::Result<()> {
+ // Test with batch smaller than the batch size (8192)
+ let small_batch_size = 512; // Less than 8192
+
+ let batches = create_and_collect_batches(small_batch_size).await?;
+
+ // Should not split small batches below the batch size
+ assert_eq!(batches.len(), 1);
+ assert_eq!(batches[0].num_rows(), small_batch_size);
+ Ok(())
+}
+
+#[tokio::test]
+async fn datasource_empty_batch_clean_termination() -> datafusion_common::Result<()> {
+ let batches = create_and_collect_batches(0).await?;
+
+ // Empty batch should result in one empty batch
+ assert_eq!(batches.len(), 1);
+ assert_eq!(batches[0].num_rows(), 0);
+ Ok(())
+}
+
+#[tokio::test]
+async fn datasource_multiple_empty_batches() -> datafusion_common::Result<()> {
+ let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
+ let empty_array = Int32Array::from_iter_values(std::iter::empty::<i32>());
+ let empty_batch =
+ RecordBatch::try_new(schema.clone(), vec![Arc::new(empty_array) as ArrayRef])?;
+
+ // Create multiple empty batches
+ let input_batches = vec![empty_batch.clone(), empty_batch.clone(), empty_batch];
+ let batches = create_and_collect_multiple_batches(input_batches).await?;
+
+ // Should preserve empty batches without issues
+ assert_eq!(batches.len(), 3);
+ for batch in &batches {
+ assert_eq!(batch.num_rows(), 0);
+ }
+ Ok(())
+}
diff --git a/datafusion/core/tests/execution/mod.rs b/datafusion/core/tests/execution/mod.rs
index f367a29017..8770b2a201 100644
--- a/datafusion/core/tests/execution/mod.rs
+++ b/datafusion/core/tests/execution/mod.rs
@@ -16,4 +16,5 @@
// under the License.
mod coop;
+mod datasource_split;
mod logical_plan;
diff --git a/datafusion/datasource/src/source.rs b/datafusion/datasource/src/source.rs
index a002d4992c..fde1944ae0 100644
--- a/datafusion/datasource/src/source.rs
+++ b/datafusion/datasource/src/source.rs
@@ -25,8 +25,10 @@ use std::sync::Arc;
use datafusion_physical_plan::execution_plan::{
Boundedness, EmissionType, SchedulingType,
};
+use datafusion_physical_plan::metrics::SplitMetrics;
use datafusion_physical_plan::metrics::{ExecutionPlanMetricsSet, MetricsSet};
use datafusion_physical_plan::projection::ProjectionExec;
+use datafusion_physical_plan::stream::BatchSplitStream;
use datafusion_physical_plan::{
DisplayAs, DisplayFormatType, ExecutionPlan, PlanProperties,
};
@@ -267,7 +269,18 @@ impl ExecutionPlan for DataSourceExec {
partition: usize,
context: Arc<TaskContext>,
) -> Result<SendableRecordBatchStream> {
- self.data_source.open(partition, Arc::clone(&context))
+ let stream = self.data_source.open(partition, Arc::clone(&context))?;
+ let batch_size = context.session_config().batch_size();
+ log::debug!(
+ "Batch splitting enabled for partition {partition}: batch_size={batch_size}"
+ );
+ let metrics = self.data_source.metrics();
+ let split_metrics = SplitMetrics::new(&metrics, partition);
+ Ok(Box::pin(BatchSplitStream::new(
+ stream,
+ batch_size,
+ split_metrics,
+ )))
}
fn metrics(&self) -> Option<MetricsSet> {
diff --git a/datafusion/physical-plan/src/metrics/baseline.rs b/datafusion/physical-plan/src/metrics/baseline.rs
index a52336108a..41d67c2917 100644
--- a/datafusion/physical-plan/src/metrics/baseline.rs
+++ b/datafusion/physical-plan/src/metrics/baseline.rs
@@ -169,6 +169,23 @@ impl SpillMetrics {
}
}
+/// Metrics for tracking [`crate::stream::BatchSplitStream`] activity
+#[derive(Debug, Clone)]
+pub struct SplitMetrics {
+ /// Number of times an input [`RecordBatch`] was split
+ pub batches_splitted: Count,
+}
+
+impl SplitMetrics {
+ /// Create a new [`SplitMetrics`]
+ pub fn new(metrics: &ExecutionPlanMetricsSet, partition: usize) -> Self {
+ Self {
+ batches_splitted: MetricBuilder::new(metrics)
+ .counter("batches_splitted", partition),
+ }
+ }
+}
+
/// Trait for things that produce output rows as a result of execution.
pub trait RecordOutput {
/// Record that some number of output rows have been produced
diff --git a/datafusion/physical-plan/src/metrics/mod.rs b/datafusion/physical-plan/src/metrics/mod.rs
index 87783eada8..d9c281bc03 100644
--- a/datafusion/physical-plan/src/metrics/mod.rs
+++ b/datafusion/physical-plan/src/metrics/mod.rs
@@ -32,7 +32,7 @@ use std::{
use datafusion_common::HashMap;
// public exports
-pub use baseline::{BaselineMetrics, RecordOutput, SpillMetrics};
+pub use baseline::{BaselineMetrics, RecordOutput, SpillMetrics, SplitMetrics};
pub use builder::MetricBuilder;
pub use custom::CustomMetricValue;
pub use value::{Count, Gauge, MetricValue, ScopedTimerGuard, Time, Timestamp};
diff --git a/datafusion/physical-plan/src/stream.rs b/datafusion/physical-plan/src/stream.rs
index 338ac7d048..773a098669 100644
--- a/datafusion/physical-plan/src/stream.rs
+++ b/datafusion/physical-plan/src/stream.rs
@@ -22,7 +22,9 @@ use std::sync::Arc;
use std::task::Context;
use std::task::Poll;
-use super::metrics::BaselineMetrics;
+#[cfg(test)]
+use super::metrics::ExecutionPlanMetricsSet;
+use super::metrics::{BaselineMetrics, SplitMetrics};
use super::{ExecutionPlan, RecordBatchStream, SendableRecordBatchStream};
use crate::displayable;
@@ -31,6 +33,7 @@ use datafusion_common::{exec_err, Result};
use datafusion_common_runtime::JoinSet;
use datafusion_execution::TaskContext;
+use futures::ready;
use futures::stream::BoxStream;
use futures::{Future, Stream, StreamExt};
use log::debug;
@@ -522,6 +525,138 @@ impl Stream for ObservedStream {
}
}
+pin_project! {
+ /// Stream wrapper that splits large [`RecordBatch`]es into smaller batches.
+ ///
+ /// This ensures upstream operators receive batches no larger than
+ /// `batch_size`, which can improve parallelism when data sources
+ /// generate very large batches.
+ ///
+ /// # Fields
+ ///
+ /// - `current_batch`: The batch currently being split, if any
+ /// - `offset`: Index of the next row to split from `current_batch`.
+ /// This tracks our position within the current batch being split.
+ ///
+ /// # Invariants
+ ///
+ /// - `offset` is always ≤ `current_batch.num_rows()` when `current_batch` is `Some`
+ /// - When `current_batch` is `None`, `offset` is always 0
+ /// - `batch_size` is always > 0
+pub struct BatchSplitStream {
+ #[pin]
+ input: SendableRecordBatchStream,
+ schema: SchemaRef,
+ batch_size: usize,
+ metrics: SplitMetrics,
+ current_batch: Option<RecordBatch>,
+ offset: usize,
+ }
+}
+
+impl BatchSplitStream {
+ /// Create a new [`BatchSplitStream`]
+ pub fn new(
+ input: SendableRecordBatchStream,
+ batch_size: usize,
+ metrics: SplitMetrics,
+ ) -> Self {
+ let schema = input.schema();
+ Self {
+ input,
+ schema,
+ batch_size,
+ metrics,
+ current_batch: None,
+ offset: 0,
+ }
+ }
+
+ /// Attempt to produce the next sliced batch from the current batch.
+ ///
+ /// Returns `Some(batch)` if a slice was produced, `None` if the current batch
+ /// is exhausted and we need to poll upstream for more data.
+ fn next_sliced_batch(&mut self) -> Option<Result<RecordBatch>> {
+ let batch = self.current_batch.take()?;
+
+ // Assert slice boundary safety - offset should never exceed batch size
+ debug_assert!(
+ self.offset <= batch.num_rows(),
+ "Offset {} exceeds batch size {}",
+ self.offset,
+ batch.num_rows()
+ );
+
+ let remaining = batch.num_rows() - self.offset;
+ let to_take = remaining.min(self.batch_size);
+ let out = batch.slice(self.offset, to_take);
+
+ self.metrics.batches_splitted.add(1);
+ self.offset += to_take;
+ if self.offset < batch.num_rows() {
+ // More data remains in this batch, store it back
+ self.current_batch = Some(batch);
+ } else {
+ // Batch is exhausted, reset offset
+ // Note: current_batch is already None since we took it at the start
+ self.offset = 0;
+ }
+ Some(Ok(out))
+ }
+
+ /// Poll the upstream input for the next batch.
+ ///
+ /// Returns the appropriate `Poll` result based on upstream state.
+ /// Small batches are passed through directly, large batches are stored
+ /// for slicing and return the first slice immediately.
+ fn poll_upstream(
+ &mut self,
+ cx: &mut Context<'_>,
+ ) -> Poll<Option<Result<RecordBatch>>> {
+ match ready!(self.input.as_mut().poll_next(cx)) {
+ Some(Ok(batch)) => {
+ if batch.num_rows() <= self.batch_size {
+ // Small batch, pass through directly
+ Poll::Ready(Some(Ok(batch)))
+ } else {
+ // Large batch, store for slicing and return first slice
+ self.current_batch = Some(batch);
+ // Immediately produce the first slice
+ match self.next_sliced_batch() {
+ Some(result) => Poll::Ready(Some(result)),
+ None => Poll::Ready(None), // Should not happen
+ }
+ }
+ }
+ Some(Err(e)) => Poll::Ready(Some(Err(e))),
+ None => Poll::Ready(None),
+ }
+ }
+}
+
+impl Stream for BatchSplitStream {
+ type Item = Result<RecordBatch>;
+
+ fn poll_next(
+ mut self: Pin<&mut Self>,
+ cx: &mut Context<'_>,
+ ) -> Poll<Option<Self::Item>> {
+ // First, try to produce a slice from the current batch
+ if let Some(result) = self.next_sliced_batch() {
+ return Poll::Ready(Some(result));
+ }
+
+ // No current batch or current batch exhausted, poll upstream
+ self.poll_upstream(cx)
+ }
+}
+
+impl RecordBatchStream for BatchSplitStream {
+ fn schema(&self) -> SchemaRef {
+ Arc::clone(&self.schema)
+ }
+}
+
#[cfg(test)]
mod test {
use super::*;
@@ -616,6 +751,44 @@ mod test {
assert!(stream.next().await.is_none());
}
+ #[tokio::test]
+ async fn batch_split_stream_basic_functionality() {
+ use arrow::array::{Int32Array, RecordBatch};
+ use futures::stream::{self, StreamExt};
+
+ let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)]));
+
+ // Create a large batch that should be split
+ let large_batch = RecordBatch::try_new(
+ Arc::clone(&schema),
+ vec![Arc::new(Int32Array::from((0..2000).collect::<Vec<_>>()))],
+ )
+ .unwrap();
+
+ // Create a stream with the large batch
+ let input_stream = stream::iter(vec![Ok(large_batch)]);
+ let adapter = RecordBatchStreamAdapter::new(Arc::clone(&schema), input_stream);
+ let batch_stream = Box::pin(adapter) as SendableRecordBatchStream;
+
+ // Create a BatchSplitStream with batch_size = 500
+ let metrics = ExecutionPlanMetricsSet::new();
+ let split_metrics = SplitMetrics::new(&metrics, 0);
+ let mut split_stream = BatchSplitStream::new(batch_stream, 500, split_metrics);
+
+ let mut total_rows = 0;
+ let mut batch_count = 0;
+
+ while let Some(result) = split_stream.next().await {
+ let batch = result.unwrap();
+ assert!(batch.num_rows() <= 500, "Batch size should not exceed 500");
+ total_rows += batch.num_rows();
+ batch_count += 1;
+ }
+
+ assert_eq!(total_rows, 2000, "All rows should be preserved");
+ assert_eq!(batch_count, 4, "Should have 4 batches of 500 rows each");
+ }
+
/// Consumes all the input's partitions into a
/// RecordBatchReceiverStream and runs it to completion
///
diff --git a/datafusion/sqllogictest/test_files/group_by.slt b/datafusion/sqllogictest/test_files/group_by.slt
index 6dcce27ad7..6dc4bd8404 100644
--- a/datafusion/sqllogictest/test_files/group_by.slt
+++ b/datafusion/sqllogictest/test_files/group_by.slt
@@ -3425,7 +3425,7 @@ physical_plan
06)----------RepartitionExec: partitioning=Hash([sn@0, amount@1], 8), input_partitions=8
07)------------AggregateExec: mode=Partial, gby=[sn@0 as sn, amount@1 as amount], aggr=[]
08)--------------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1
-09)----------------DataSourceExec: partitions=1, partition_sizes=[1]
+09)----------------DataSourceExec: partitions=1, partition_sizes=[2]
query IRI
SELECT s.sn, s.amount, 2*s.sn
@@ -3494,9 +3494,9 @@ physical_plan
06)----------RepartitionExec: partitioning=Hash([sn@0, amount@1], 8), input_partitions=8
07)------------AggregateExec: mode=Partial, gby=[sn@1 as sn, amount@2 as amount], aggr=[sum(l.amount)]
08)--------------NestedLoopJoinExec: join_type=Inner, filter=sn@0 >= sn@1, projection=[amount@1, sn@2, amount@3]
-09)----------------DataSourceExec: partitions=1, partition_sizes=[1]
+09)----------------DataSourceExec: partitions=1, partition_sizes=[2]
10)----------------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1
-11)------------------DataSourceExec: partitions=1, partition_sizes=[1]
+11)------------------DataSourceExec: partitions=1, partition_sizes=[2]
query IRR
SELECT r.sn, SUM(l.amount), r.amount
@@ -3643,7 +3643,7 @@ physical_plan
08)--------------RepartitionExec: partitioning=RoundRobinBatch(8), input_partitions=1
09)----------------ProjectionExec: expr=[zip_code@0 as zip_code, country@1 as country, sn@2 as sn, ts@3 as ts, currency@4 as currency, amount@5 as amount, sum(l.amount) ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING@6 as sum_amount]
10)------------------BoundedWindowAggExec: wdw=[sum(l.amount) ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING: Field { name: "sum(l.amount) ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING", data_type: Float64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }, frame: ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING], mode=[Sorted]
-11)--------------------DataSourceExec: partitions=1, partition_sizes=[1]
+11)--------------------DataSourceExec: partitions=1, partition_sizes=[2]
query ITIPTRR
@@ -4535,19 +4535,20 @@ LIMIT 5
query ITIPTR rowsort
SELECT r.*
FROM sales_global_with_pk as l, sales_global_with_pk as r
+ORDER BY 1, 2, 3, 4, 5, 6
LIMIT 5
----
0 GRC 0 2022-01-01T06:00:00 EUR 30
-1 FRA 1 2022-01-01T08:00:00 EUR 50
-1 FRA 3 2022-01-02T12:00:00 EUR 200
-1 TUR 2 2022-01-01T11:30:00 TRY 75
-1 TUR 4 2022-01-03T10:00:00 TRY 100
+0 GRC 0 2022-01-01T06:00:00 EUR 30
+0 GRC 0 2022-01-01T06:00:00 EUR 30
+0 GRC 0 2022-01-01T06:00:00 EUR 30
+0 GRC 0 2022-01-01T06:00:00 EUR 30
# Create a table with timestamp data
statement ok
CREATE TABLE src_table (
- t1 TIMESTAMP,
- c2 INT
+ t1 TIMESTAMP,
+ c2 INT
) AS VALUES
('2020-12-10T00:00:00.00Z', 0),
('2020-12-11T00:00:00.00Z', 1),
@@ -4592,8 +4593,8 @@ STORED AS CSV;
# Create a table from the generated CSV files:
statement ok
CREATE EXTERNAL TABLE timestamp_table (
- t1 TIMESTAMP,
- c2 INT,
+ t1 TIMESTAMP,
+ c2 INT,
)
STORED AS CSV
LOCATION 'test_files/scratch/group_by/timestamp_table'
@@ -5176,8 +5177,8 @@ physical_plan
02)--AggregateExec: mode=Single, gby=[date_bin(IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 120000000000 }, ts@0, 946684800000000000) as date_bin(IntervalMonthDayNano("IntervalMonthDayNano { months: 0, days: 0, nanoseconds: 120000000000 }"),keywords_stream.ts,Utf8("2000-01-01"))], aggr=[count(keywords_stream.keyword)]
03)----CoalesceBatchesExec: target_batch_size=2
04)------HashJoinExec: mode=CollectLeft, join_type=RightSemi, on=[(keyword@0, keyword@1)]
-05)--------DataSourceExec: partitions=1, partition_sizes=[1]
-06)--------DataSourceExec: partitions=1, partition_sizes=[1]
+05)--------DataSourceExec: partitions=1, partition_sizes=[3]
+06)--------DataSourceExec: partitions=1, partition_sizes=[3]
query PI
SELECT
@@ -5219,17 +5220,17 @@ statement ok
create table t(a int, b bytea) as values (1, 0xa), (1, 0xa), (2, null), (null, 0xb), (null, 0xb);
query I?I
-select a, b, count(*) from t group by grouping sets ((a, b), (a), (b));
+select a, b, count(*) from t group by grouping sets ((a, b), (a), (b)) order by a, b;
----
1 0a 2
-2 NULL 1
-NULL 0b 2
1 NULL 2
2 NULL 1
-NULL NULL 2
+2 NULL 1
NULL 0a 2
-NULL NULL 1
NULL 0b 2
+NULL 0b 2
+NULL NULL 2
+NULL NULL 1
statement ok
drop table t;
@@ -5239,13 +5240,13 @@ statement ok
create table t(a int, b bytea) as values (1, 0xa), (1, 0xa), (2, 0xb), (3, 0xb), (3, 0xb);
query I?I
-select a, b, count(*) from t group by grouping sets ((a, b), (a), (b));
+select a, b, count(*) from t group by grouping sets ((a, b), (a), (b)) order by a, b;
----
1 0a 2
-2 0b 1
-3 0b 2
1 NULL 2
+2 0b 1
2 NULL 1
+3 0b 2
3 NULL 2
NULL 0a 2
NULL 0b 3
diff --git a/datafusion/sqllogictest/test_files/joins.slt b/datafusion/sqllogictest/test_files/joins.slt
index 2fabdce19f..6c40a71fa6 100644
--- a/datafusion/sqllogictest/test_files/joins.slt
+++ b/datafusion/sqllogictest/test_files/joins.slt
@@ -24,7 +24,7 @@ statement ok
set datafusion.execution.target_partitions = 2;
statement ok
-set datafusion.execution.batch_size = 2;
+set datafusion.execution.batch_size = 8192;
statement ok
set datafusion.explain.logical_plan_only = true;
@@ -549,64 +549,64 @@ statement ok
set datafusion.optimizer.repartition_joins = true
query ITT nosort
-SELECT t1_id, t1_name, t2_name FROM t1, t2 ORDER BY t1_id
+SELECT t1_id, t1_name, t2_name FROM t1, t2 ORDER BY t1_id, t1_name, t2_name
----
-11 a z
-11 a y
-11 a x
11 a w
-22 b z
-22 b y
-22 b x
+11 a x
+11 a y
+11 a z
22 b w
-33 c z
-33 c y
-33 c x
+22 b x
+22 b y
+22 b z
33 c w
-44 d z
-44 d y
-44 d x
+33 c x
+33 c y
+33 c z
44 d w
+44 d x
+44 d y
+44 d z
query ITT nosort
-SELECT t1_id, t1_name, t2_name FROM t1, t2 WHERE 1=1 ORDER BY t1_id
+SELECT t1_id, t1_name, t2_name FROM t1, t2 WHERE 1=1 ORDER BY t1_id, t1_name, t2_name
----
-11 a z
-11 a y
-11 a x
11 a w
-22 b z
-22 b y
-22 b x
+11 a x
+11 a y
+11 a z
22 b w
-33 c z
-33 c y
-33 c x
+22 b x
+22 b y
+22 b z
33 c w
-44 d z
-44 d y
-44 d x
+33 c x
+33 c y
+33 c z
44 d w
+44 d x
+44 d y
+44 d z
query ITT nosort
-SELECT t1_id, t1_name, t2_name FROM t1 CROSS JOIN t2 ORDER BY t1_id
+SELECT t1_id, t1_name, t2_name FROM t1 CROSS JOIN t2 ORDER BY t1_id, t1_name, t2_name
----
-11 a z
-11 a y
-11 a x
11 a w
-22 b z
-22 b y
-22 b x
+11 a x
+11 a y
+11 a z
22 b w
-33 c z
-33 c y
-33 c x
+22 b x
+22 b y
+22 b z
33 c w
-44 d z
-44 d y
-44 d x
+33 c x
+33 c y
+33 c z
44 d w
+44 d x
+44 d y
+44 d z
query ITITI rowsort
SELECT * FROM (SELECT t1_id, t1_name FROM t1 UNION ALL SELECT t1_id, t1_name FROM t1) AS t1 CROSS JOIN t2
@@ -685,44 +685,44 @@ statement ok
set datafusion.optimizer.repartition_joins = false
query ITT nosort
-SELECT t1_id, t1_name, t2_name FROM t1, t2 ORDER BY t1_id
+SELECT t1_id, t1_name, t2_name FROM t1, t2 ORDER BY t1_id, t1_name, t2_name
----
-11 a z
-11 a y
-11 a x
11 a w
-22 b z
-22 b y
-22 b x
+11 a x
+11 a y
+11 a z
22 b w
-33 c z
-33 c y
-33 c x
+22 b x
+22 b y
+22 b z
33 c w
-44 d z
-44 d y
-44 d x
+33 c x
+33 c y
+33 c z
44 d w
+44 d x
+44 d y
+44 d z
query ITT nosort
-SELECT t1_id, t1_name, t2_name FROM t1, t2 WHERE 1=1 ORDER BY t1_id
+SELECT t1_id, t1_name, t2_name FROM t1, t2 WHERE 1=1 ORDER BY t1_id, t1_name, t2_name
----
-11 a z
-11 a y
-11 a x
11 a w
-22 b z
-22 b y
-22 b x
+11 a x
+11 a y
+11 a z
22 b w
-33 c z
-33 c y
-33 c x
+22 b x
+22 b y
+22 b z
33 c w
-44 d z
-44 d y
-44 d x
+33 c x
+33 c y
+33 c z
44 d w
+44 d x
+44 d y
+44 d z
query ITT nosort
SELECT t1_id, t1_name, t2_name FROM t1 CROSS JOIN t2 ORDER BY t1_id
@@ -2066,6 +2066,7 @@ SELECT join_t1.t1_id, join_t2.t2_id
FROM join_t1
INNER JOIN join_t2 ON join_t1.t1_id > join_t2.t2_id
WHERE join_t1.t1_id > 10 AND join_t2.t2_int > 1
+ORDER BY 1
----
22 11
33 11
@@ -2105,6 +2106,7 @@ SELECT join_t1.t1_id, join_t2.t2_id
FROM (select t1_id from join_t1 where join_t1.t1_id > 22) as join_t1
RIGHT JOIN (select t2_id from join_t2 where join_t2.t2_id > 11) as join_t2
ON join_t1.t1_id < join_t2.t2_id
+ORDER BY 1, 2
----
33 44
33 55
@@ -2151,6 +2153,7 @@ WHERE EXISTS (
FROM join_t2
WHERE join_t1.t1_id + 1 > join_t2.t2_id * 2
)
+ORDER BY 1
----
22 b 2
33 c 3
@@ -2167,6 +2170,7 @@ WHERE EXISTS (
FROM join_t2
WHERE join_t1.t1_id + 1 > join_t2.t2_id * 2
)
+ORDER BY 1
----
22 b 2
33 c 3
@@ -3871,8 +3875,8 @@ physical_plan
02)--CoalesceBatchesExec: target_batch_size=3
03)----HashJoinExec: mode=CollectLeft, join_type=Left, on=[(b@1, b@1)]
04)------SortExec: TopK(fetch=10), expr=[b@1 ASC NULLS LAST], preserve_partitioning=[false]
-05)--------DataSourceExec: partitions=1, partition_sizes=[1]
-06)------DataSourceExec: partitions=1, partition_sizes=[1]
+05)--------DataSourceExec: partitions=1, partition_sizes=[2]
+06)------DataSourceExec: partitions=1, partition_sizes=[2]
@@ -3928,8 +3932,8 @@ physical_plan
01)ProjectionExec: expr=[a@2 as a, b@3 as b, a@0 as a, b@1 as b]
02)--CoalesceBatchesExec: target_batch_size=3
03)----HashJoinExec: mode=CollectLeft, join_type=Left, on=[(b@1, b@1)]
-04)------DataSourceExec: partitions=1, partition_sizes=[1]
-05)------DataSourceExec: partitions=1, partition_sizes=[1]
+04)------DataSourceExec: partitions=1, partition_sizes=[2]
+05)------DataSourceExec: partitions=1, partition_sizes=[2]
# Null build indices:
@@ -3989,8 +3993,8 @@ physical_plan
02)--CoalesceBatchesExec: target_batch_size=3
03)----HashJoinExec: mode=CollectLeft, join_type=Left, on=[(b@1, b@1)]
04)------SortExec: TopK(fetch=10), expr=[b@1 ASC NULLS LAST], preserve_partitioning=[false]
-05)--------DataSourceExec: partitions=1, partition_sizes=[1]
-06)------DataSourceExec: partitions=1, partition_sizes=[1]
+05)--------DataSourceExec: partitions=1, partition_sizes=[2]
+06)------DataSourceExec: partitions=1, partition_sizes=[2]
# Test CROSS JOIN LATERAL syntax (planning)
@@ -4190,8 +4194,8 @@ logical_plan
physical_plan
01)CoalesceBatchesExec: target_batch_size=3, fetch=2
02)--HashJoinExec: mode=CollectLeft, join_type=Full, on=[(c1@0, c1@0)]
-03)----DataSourceExec: partitions=1, partition_sizes=[1]
-04)----DataSourceExec: partitions=1, partition_sizes=[1]
+03)----DataSourceExec: partitions=1, partition_sizes=[2]
+04)----DataSourceExec: partitions=1, partition_sizes=[2]
## Test join.on.is_empty() && join.filter.is_some()
query TT
@@ -4205,8 +4209,8 @@ logical_plan
physical_plan
01)GlobalLimitExec: skip=0, fetch=2
02)--NestedLoopJoinExec: join_type=Full, filter=c2@0 >= c2@1
-03)----DataSourceExec: partitions=1, partition_sizes=[1]
-04)----DataSourceExec: partitions=1, partition_sizes=[1]
+03)----DataSourceExec: partitions=1, partition_sizes=[2]
+04)----DataSourceExec: partitions=1, partition_sizes=[2]
## Test !join.on.is_empty() && join.filter.is_some()
query TT
@@ -4220,8 +4224,8 @@ logical_plan
physical_plan
01)CoalesceBatchesExec: target_batch_size=3, fetch=2
02)--HashJoinExec: mode=CollectLeft, join_type=Full, on=[(c1@0, c1@0)], filter=c2@0 >= c2@1
-03)----DataSourceExec: partitions=1, partition_sizes=[1]
-04)----DataSourceExec: partitions=1, partition_sizes=[1]
+03)----DataSourceExec: partitions=1, partition_sizes=[2]
+04)----DataSourceExec: partitions=1, partition_sizes=[2]
## Add more test cases for join limit pushdown
statement ok
@@ -4429,11 +4433,9 @@ physical_plan
04)------CoalescePartitionsExec
05)--------CoalesceBatchesExec: target_batch_size=3
06)----------FilterExec: b@1 > 3, projection=[a@0]
-07)------------RepartitionExec: partitioning=RoundRobinBatch(2), input_partitions=1
-08)--------------DataSourceExec: partitions=1, partition_sizes=[1]
-09)------SortExec: expr=[c@2 DESC], preserve_partitioning=[true]
-10)--------RepartitionExec: partitioning=RoundRobinBatch(2), input_partitions=1
-11)----------DataSourceExec: partitions=1, partition_sizes=[1]
+07)------------DataSourceExec: partitions=2, partition_sizes=[1, 1]
+08)------SortExec: expr=[c@2 DESC], preserve_partitioning=[true]
+09)--------DataSourceExec: partitions=2, partition_sizes=[1, 1]
query TT
explain select * from test where a in (select a from test where b > 3) order by c desc nulls last;
@@ -4453,11 +4455,9 @@ physical_plan
04)------CoalescePartitionsExec
05)--------CoalesceBatchesExec: target_batch_size=3
06)----------FilterExec: b@1 > 3, projection=[a@0]
-07)------------RepartitionExec: partitioning=RoundRobinBatch(2), input_partitions=1
-08)--------------DataSourceExec: partitions=1, partition_sizes=[1]
-09)------SortExec: expr=[c@2 DESC NULLS LAST], preserve_partitioning=[true]
-10)--------RepartitionExec: partitioning=RoundRobinBatch(2), input_partitions=1
-11)----------DataSourceExec: partitions=1, partition_sizes=[1]
+07)------------DataSourceExec: partitions=2, partition_sizes=[1, 1]
+08)------SortExec: expr=[c@2 DESC NULLS LAST], preserve_partitioning=[true]
+09)--------DataSourceExec: partitions=2, partition_sizes=[1, 1]
query III
select * from test where a in (select a from test where b > 3) order by c desc nulls first;
diff --git a/datafusion/sqllogictest/test_files/subquery.slt b/datafusion/sqllogictest/test_files/subquery.slt
index 796570633f..ed73eecda0 100644
--- a/datafusion/sqllogictest/test_files/subquery.slt
+++ b/datafusion/sqllogictest/test_files/subquery.slt
@@ -210,9 +210,9 @@ physical_plan
08)--------------RepartitionExec: partitioning=Hash([t2_id@0], 4), input_partitions=4
09)----------------AggregateExec: mode=Partial, gby=[t2_id@0 as t2_id], aggr=[sum(t2.t2_int)]
10)------------------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
-11)--------------------DataSourceExec: partitions=1, partition_sizes=[1]
+11)--------------------DataSourceExec: partitions=1, partition_sizes=[2]
12)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
-13)--------DataSourceExec: partitions=1, partition_sizes=[1]
+13)--------DataSourceExec: partitions=1, partition_sizes=[2]
query II rowsort
SELECT t1_id, (SELECT sum(t2_int) FROM t2 WHERE t2.t2_id = t1.t1_id) as t2_sum from t1
@@ -245,9 +245,9 @@ physical_plan
08)--------------RepartitionExec: partitioning=Hash([t2_id@0], 4), input_partitions=4
09)----------------AggregateExec: mode=Partial, gby=[t2_id@0 as t2_id], aggr=[sum(t2.t2_int * Float64(1))]
10)------------------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
-11)--------------------DataSourceExec: partitions=1, partition_sizes=[1]
+11)--------------------DataSourceExec: partitions=1, partition_sizes=[2]
12)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
-13)--------DataSourceExec: partitions=1, partition_sizes=[1]
+13)--------DataSourceExec: partitions=1, partition_sizes=[2]
query IR rowsort
SELECT t1_id, (SELECT sum(t2_int * 1.0) + 1 FROM t2 WHERE t2.t2_id = t1.t1_id) as t2_sum from t1
@@ -280,9 +280,9 @@ physical_plan
08)--------------RepartitionExec: partitioning=Hash([t2_id@0], 4), input_partitions=4
09)----------------AggregateExec: mode=Partial, gby=[t2_id@0 as t2_id], aggr=[sum(t2.t2_int)]
10)------------------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
-11)--------------------DataSourceExec: partitions=1, partition_sizes=[1]
+11)--------------------DataSourceExec: partitions=1, partition_sizes=[2]
12)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
-13)--------DataSourceExec: partitions=1, partition_sizes=[1]
+13)--------DataSourceExec: partitions=1, partition_sizes=[2]
query II rowsort
SELECT t1_id, (SELECT sum(t2_int) FROM t2 WHERE t2.t2_id = t1.t1_id group by t2_id, 'a') as t2_sum from t1
@@ -318,9 +318,9 @@ physical_plan
10)------------------RepartitionExec: partitioning=Hash([t2_id@0], 4), input_partitions=4
11)--------------------AggregateExec: mode=Partial, gby=[t2_id@0 as t2_id], aggr=[sum(t2.t2_int)]
12)----------------------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
-13)------------------------DataSourceExec: partitions=1, partition_sizes=[1]
+13)------------------------DataSourceExec: partitions=1, partition_sizes=[2]
14)------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
-15)--------DataSourceExec: partitions=1, partition_sizes=[1]
+15)--------DataSourceExec: partitions=1, partition_sizes=[2]
query II rowsort
SELECT t1_id, (SELECT sum(t2_int) FROM t2 WHERE t2.t2_id = t1.t1_id having sum(t2_int) < 3) as t2_sum from t1
@@ -1193,9 +1193,9 @@ physical_plan
02)--FilterExec: t1_id@0 > 40 OR NOT mark@3, projection=[t1_id@0, t1_name@1, t1_int@2]
03)----CoalesceBatchesExec: target_batch_size=2
04)------HashJoinExec: mode=CollectLeft, join_type=LeftMark, on=[(t1_id@0, t2_id@0)]
-05)--------DataSourceExec: partitions=1, partition_sizes=[1]
+05)--------DataSourceExec: partitions=1, partition_sizes=[2]
06)--------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
-07)----------DataSourceExec: partitions=1, partition_sizes=[1]
+07)----------DataSourceExec: partitions=1, partition_sizes=[2]
statement ok
set datafusion.explain.logical_plan_only = true;
diff --git a/datafusion/sqllogictest/test_files/union.slt b/datafusion/sqllogictest/test_files/union.slt
index 4b68419d8b..6097444bc5 100644
--- a/datafusion/sqllogictest/test_files/union.slt
+++ b/datafusion/sqllogictest/test_files/union.slt
@@ -915,19 +915,19 @@ physical_plan
03)----SortExec: expr=[y@0 ASC NULLS LAST], preserve_partitioning=[true]
04)------ProjectionExec: expr=[CAST(y@0 AS Int64) as y]
05)--------RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
-06)----------DataSourceExec: partitions=1, partition_sizes=[1]
+06)----------DataSourceExec: partitions=1, partition_sizes=[2]
07)----SortExec: expr=[y@0 ASC NULLS LAST], preserve_partitioning=[false]
08)------DataSourceExec: partitions=1, partition_sizes=[1]
# optimize_subquery_sort in create_relation removes Sort so the result is not sorted.
query I
-SELECT * FROM v1;
+SELECT * FROM v1 ORDER BY 1;
----
-20
-40
+1
3
3
-1
+20
+40
query TT
explain SELECT * FROM v1;
@@ -942,7 +942,7 @@ physical_plan
01)UnionExec
02)--ProjectionExec: expr=[CAST(y@0 AS Int64) as y]
03)----RepartitionExec: partitioning=RoundRobinBatch(4), input_partitions=1
-04)------DataSourceExec: partitions=1, partition_sizes=[1]
+04)------DataSourceExec: partitions=1, partition_sizes=[2]
05)--DataSourceExec: partitions=1, partition_sizes=[1]
statement count 0
diff --git a/datafusion/sqllogictest/test_files/window.slt b/datafusion/sqllogictest/test_files/window.slt
index 103c4ac81f..82de113028 100644
--- a/datafusion/sqllogictest/test_files/window.slt
+++ b/datafusion/sqllogictest/test_files/window.slt
@@ -4341,6 +4341,9 @@ LIMIT 5;
24 31
14 94
+statement ok
+set datafusion.execution.batch_size = 100;
+
# Tests schema and data are in sync for mixed nulls and not nulls values for builtin window function
query T
select lag(a) over (order by a ASC NULLS FIRST) as x1
@@ -4938,11 +4941,11 @@ FROM (SELECT c1, c2, ROW_NUMBER() OVER() as rn
FROM t
LIMIT 5)
GROUP BY rn
-ORDER BY rn;
+ORDER BY 1, 2, 3
----
1 a 1
-2 b 2
1 a 3
+2 b 2
3 NULL 4
NULL a4 5
@@ -5181,6 +5184,10 @@ order by c1;
3 1 1
3 10 2
+
+statement ok
+set datafusion.execution.batch_size = 1;
+
# push filter since it uses a partition column
query TT
explain select c1, c2, rank
@@ -5507,6 +5514,7 @@ physical_plan
02)--WindowAggExec: wdw=[sum(aggregate_test_100_ordered.c9) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING: Ok(Field { name: "sum(aggregate_test_100_ordered.c9) ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING", data_type: UInt64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Rows, start_bound: Preceding(UInt64(NULL)), end_bound: Following(UInt64(NULL)), is_causal: false }]
03)----DataSourceExec: file_groups={1 group: [[WORKSPACE_ROOT/testing/data/csv/aggregate_test_100.csv]]}, projection=[c9], file_type=csv, has_header=true
+
query TT
EXPLAIN SELECT c1, MIN(c5) OVER(PARTITION BY c1) as min_c5 FROM aggregate_test_100_ordered ORDER BY c1, min_c5 DESC NULLS LAST;
----